0%

92. Reverse Linked List II

O(n) time O(1) space
这道题的思路跟普通的reverse不一样!!
curr是固定的,永远指向初始的第m个结点,anchor也是固定的,永远是curr的前继结点
每次curr都是和它的succ交换,然后让next的下一个指向anchor的下一个结点,最后anchor的下一个指向那个succ结点

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int m, int n) {
ListNode dummy_head(0), *anchor = &dummy_head;
dummy_head.next = head;
n -= m;
while (--m > 0)
anchor = anchor->next;
auto curr = anchor->next;
while (n-- > 0) {
auto succ = curr->next;
curr->next = succ->next;
succ->next = anchor->next;
anchor->next = succ;
}
return dummy_head.next;
}
};