Skip to content

Commit 1aac8c0

Browse files
committed
2
1 parent 6ac02f2 commit 1aac8c0

File tree

1 file changed

+42
-43
lines changed

1 file changed

+42
-43
lines changed

ReverseNodesink-Group/ReverseNodesink-Group.cpp

+42-43
Original file line numberDiff line numberDiff line change
@@ -9,53 +9,52 @@
99
class Solution {
1010
public:
1111
ListNode *reverseKGroup(ListNode *head, int k) {
12-
// Start typing your C/C++ solution below
13-
// DO NOT write int main() function
14-
15-
//
16-
// only travel the list for one time
17-
//
18-
19-
ListNode node(0);
20-
node.next = head;
21-
ListNode *slow = head;
22-
ListNode *fast = &node;
23-
24-
for (int i = 0; i < k; i++) {
25-
if (fast && fast->next) fast = fast->next;
26-
else return head;
12+
ListNode* node = head;
13+
int len = 0;
14+
while (node) {
15+
len++;
16+
node = node->next;
17+
}
18+
if (k > len) {
19+
return head;
2720
}
2821

29-
bool kRemaind = true;
30-
bool getHead = false;
31-
ListNode *newHead = NULL;
22+
ListNode prevhead(0);
23+
prevhead.next = head;
3224

33-
while (kRemaind) {
34-
ListNode *tail = slow;
35-
ListNode *prev = NULL;
36-
ListNode *next = NULL;
37-
38-
for (int i = 0; i < k; i++) {
39-
next = slow->next;
40-
slow->next = prev;
41-
prev = slow;
42-
slow = next;
43-
44-
if (fast && fast->next)
45-
fast = fast->next;
46-
else
47-
kRemaind = false;
25+
ListNode* curr = head;
26+
ListNode* prev = &prevhead;
27+
28+
while (curr) {
29+
int count = k - 1;
30+
ListNode* last = curr;
31+
while (count && last) {
32+
count--;
33+
last = last->next;
4834
}
49-
if (kRemaind)
50-
tail->next = fast;
51-
else
52-
tail->next = slow;
53-
54-
if (!getHead) {
55-
newHead = prev;
56-
getHead = true;
35+
if (count == 0 && last) {
36+
ListNode* next = last->next;
37+
last->next = NULL;
38+
ListNode* l = reverse(curr);
39+
curr->next = next;
40+
prev->next = l;
41+
prev = curr;
42+
curr = next;
43+
} else {
44+
break;
5745
}
5846
}
59-
return newHead;
47+
return prevhead.next;
48+
}
49+
50+
ListNode* reverse(ListNode* head) {
51+
ListNode prevhead(0);
52+
while (head) {
53+
ListNode* next = head->next;
54+
head->next = prevhead.next;
55+
prevhead.next = head;
56+
head = next;
57+
}
58+
return prevhead.next;
6059
}
61-
};
60+
};

0 commit comments

Comments
 (0)