题解 | #链表内指定区间反转#
链表内指定区间反转
http://www.nowcoder.com/practice/b58434e200a648c589ca2063f1faf58c
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
#
# @param head ListNode类
# @param m int整型
# @param n int整型
# @return ListNode类
#
class Solution:
def reverseBetween(self , head: ListNode, m: int, n: int) -> ListNode:
dummy = ListNode(-1)
dummy.next = head
a, d = dummy, dummy
for _ in range(m - 1):
a = a.next
b = a.next
for _ in range(n):
d = d.next
c = d.next
pre = b
cur = b.next
while cur != c:
tmp = cur.next
cur.next = pre
pre = cur
cur = tmp
a.next = d
b.next = c
return dummy.next
最后返回的不能是head,必须要返回dummy.next 不一样的
解法链接