Skip to content

Commit a1746fb

Browse files
committed
reverse_nodes_in_k-Group.cpp
1 parent b23b791 commit a1746fb

File tree

1 file changed

+70
-0
lines changed

1 file changed

+70
-0
lines changed

reverse_nodes_in_k-Group.cpp

+70
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,70 @@
1+
/**
2+
* Definition for singly-linked list.
3+
* struct ListNode {
4+
* int val;
5+
* ListNode *next;
6+
* ListNode(int x) : val(x), next(NULL) {}
7+
* };
8+
*/
9+
class Solution {
10+
public:
11+
ListNode* reverseKGroup(ListNode* head, int k) {
12+
if (head == nullptr || head->next == nullptr || k == 1)
13+
return head;
14+
15+
ListNode* one = head;
16+
ListNode* oneBackup = one;
17+
ListNode* two = one->next;
18+
ListNode* three = two->next;
19+
ListNode* nextHead = exist(one, k);
20+
21+
if (nextHead)
22+
head = nextHead;
23+
else
24+
return head;
25+
26+
while (1)
27+
{
28+
bool end = false;
29+
30+
ListNode* nextHead = exist(one, 2 * k);
31+
if (nextHead)
32+
one->next = nextHead;
33+
else
34+
end = true;
35+
36+
for(int i = 0; i < k - 2; ++i)
37+
{
38+
two->next = one;
39+
one = two;
40+
two = three;
41+
three = three->next;
42+
}
43+
two->next = one;
44+
45+
if (end)
46+
{
47+
oneBackup->next = three;
48+
break;
49+
}
50+
51+
one = oneBackup = three;
52+
two = one->next;
53+
three = two->next;
54+
}
55+
return head;
56+
}
57+
58+
ListNode* exist(ListNode* head, int k)
59+
{
60+
for(int i = 0; i < k - 1; ++i)
61+
{
62+
if (head == nullptr)
63+
{
64+
return nullptr;
65+
}
66+
head = head->next;
67+
}
68+
return head;
69+
}
70+
};

0 commit comments

Comments
 (0)