【leetcode】92. 反转链表2
文章目录
- 题目
- 题解
题目
92. 反转链表2
给你单链表的头指针 head 和两个整数 left 和 right ,其中 left <= right 。请你反转从位置 left 到位置 right 的链表节点,返回 反转后的链表 。
题解
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):def reverseBetween(self, head, left, right):""":type head: Optional[ListNode]:type left: int:type right: int:rtype: Optional[ListNode]"""dummy = ListNode(0, head)p0 = dummyif not head or right - left == 0:return headfor _ in range(left - 1):p0 = p0.nextcur = p0.nextpre = Nonefor _ in range(left, right + 1):tmp = cur.nextcur.next = prepre = curcur = tmpp0.next.next = curp0.next = prereturn dummy.next