0%

92. 反转链表 II

92. 反转链表 II

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
27
28
29
30
31
32
33
34
35
36
37
38
39
40
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode pseudoHead;
ListNode* pre = &pseudoHead;
pre->next = head;
int count = 1;
while(head)
{
if(count == left)
break;
pre = head;
head = head->next;
++count;
}
ListNode* pt = nullptr;
while(head)
{
auto next = head->next;
head->next = pt;
pt = head;
head = next;
if(count++ == right)
break;
}
pre->next->next = head;
pre->next = pt;
return pseudoHead.next;
}
};

边遍历边顺便反转,事实上也是遍历一次,比关解方法一中先找左右再切断要好。

方法2

好绕,建议画图,head永远是那个点,会换了几次后换到最后

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
27
28
29
30
31
32
33
34
35
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* reverseBetween(ListNode* head, int left, int right) {
ListNode pseudoHead;
ListNode* pre = &pseudoHead;
pre->next = head;
int count = 1;
while(count != left)
{
pre = head;
head = head->next;
++count;
}
ListNode* next;
while(count != right)
{
next = head->next;
head->next = next->next;
next->next = pre->next;
pre->next = next;
++count;
}
return pseudoHead.next;
}
};