0%

25. K 个一组翻转链表

25. K 个一组翻转链表

递归

递归栈需要O(n / k)的空间复杂度

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
/**
* 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* reverseKGroup(ListNode* head, int k) {
if(!head)
return nullptr;
auto tail = head;
ListNode* pre = nullptr;
ListNode* pt = head;
for(int i = 0; i < k; ++i)
if(!pt)
return head;
else
pt = pt->next;
for(int i = 0; i < k; ++i)
{
if(!head)
break;
auto next = head->next;
head->next = pre;
pre = head;
head = next;
}
tail->next = reverseKGroup(head, k);
return pre;
}
};

迭代

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
41
42
43
44
45
46
47
48
49
/**
* 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* reverseKGroup(ListNode* head, int k) {
ListNode* pseudoHead = new ListNode();
pseudoHead->next = head;
ListNode* tail;
auto pre = pseudoHead;
while(pre)
{
ListNode* hair = pre;
for(int i = 0; i < k; ++i)
{
pre = pre->next;
if(!pre)
return pseudoHead->next;
}
auto next = pre->next;
tie(head, tail) = reverse(hair->next, next);
hair->next = head;
tail->next = next;
pre = tail;
}
return pseudoHead->next;
}
private:
pair<ListNode*, ListNode*> reverse(ListNode* head, ListNode* tail)
{
ListNode* pre = nullptr;
ListNode* pt = head;
while(pt != tail)
{
auto next = pt->next;
pt->next = pre;
pre = pt;
pt = next;
}
return {pre, 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
36
37
38
39
40
41
42
43
44
45
46
47
48
49
/**
* 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* reverseKGroup(ListNode* head, int k) {
if(k == 1)
return head;
ListNode ret;
ListNode *dummyHead{&ret};
ret.next = head;
auto pre = dummyHead;
int count{k};
while(head)
{
auto tmp = head;
int c = k;
while(c--)
{
if(!tmp)
return ret.next;
tmp = tmp->next;
}
while(--count)
{
auto next = head->next;
if(next)
{
head->next = next->next;
next->next = pre->next;
}
else
head->next = nullptr;
pre->next = next;
}
pre = head;
head = head->next;
count = k;
}
return ret.next;
}
};