模仿前面reverse nodes in k-group写的,代码如下:
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, x):
# self.val = x
# self.next = None
class Solution(object):
def reverseBetween(self, head, m, n):
"""
:type head: ListNode
:type m: int
:type n: int
:rtype: ListNode
"""
if not head or not head.next:
return head
dummy = ListNode(-1)
dummy.next = head
pre = dummy
l = dummy
r = head
k = n - m + 1
pm = m-1
while n:
r = r.next
n -= 1
while m:
l = l.next
m -= 1
while pm:
pre = pre.next
pm -= 1
pr, curr = r, l
while k:
curr.next, curr, pr = pr, curr.next, curr
k -= 1
pre.next = pr
return dummy.next
网友评论