Leetcode 92. Reverse Linked List II
Reverse a linked list from position m to n. Do it in-place and in one-pass.
For example:
Given 1->2->3->4->5->NULL
, m = 2 and n = 4,
return 1->4->3->2->5->NULL
.
Note:
Given m, n satisfy the following condition:
1 ≤ m ≤ n ≤ length of list.
本题的答案来自书影的博客。
思路其实很简单,Reverse Linked List 一题中我们已经学会了如何reverse linked list。这一题的关键在于中间部分要reverse,然后还要讲头尾按照合适的关系接起来。比如下图就显示了运行到L26的状态。注意一个处理的细节就是在L13-L16的循环前面,我们并没有使用常用的dummy.next = head这一句。因为如果m=1的话,dummy最后并不指向node1。
然后的处理方式就和reverse linked list差不多了。只不过注意保存最后需要连接起来的那几个node。
1 class Solution(object): 2 def reverseBetween(self, head, m, n): 3 """ 4 :type head: ListNode 5 :type m: int 6 :type n: int 7 :rtype: ListNode 8 """ 9 dummy = ListNode(0) 10 p = dummy 11 q = head 12 13 for i in range(m-1): 14 p.next = q 15 q = q.next 16 p = p.next 17 18 start = None 19 end = q 20 tmp = None 21 22 for x in range(m, n+1): 23 tmp = q.next 24 q.next = start 25 start = q 26 q = tmp 27 28 p.next = start 29 end.next = tmp 30 31 return dummy.next