leetcode------Reverse Linked List II
标题: | Reverse Linked List II |
通过率: | 26.2% |
难度: | 中等 |
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.
单链表的逆序,遍历一遍全部逆序完成,本题不是全部逆序,是部分逆序。只用记录逆序开始点和结束点即可逆序过程如下图:
初始状态:
head->next = prev;
prev = head;
head = next;
next = head->next
第一次结束,如上图。
整个过程是一个循环的过程,如下图:
具体代码如下:
1 class Solution: 2 def reverseBetween(self, head, m, n): 3 diff, dummy, current= n - m, ListNode(0), head 4 dummy.next = head 5 last_unswapped = dummy 6 while current != None and m > 1: 7 current, last_unswapped, m = current.next, current, m - 1 8 prev, first_swapped = last_unswapped, current 9 while current != None and diff >= 0: 10 tmp = current.next 11 current.next = prev 12 prev = current 13 current = tmp 14 diff -= 1 15 last_unswapped.next, first_swapped.next = prev, current 16 return dummy.next