File tree 1 file changed +42
-43
lines changed
1 file changed +42
-43
lines changed Original file line number Diff line number Diff line change 9
9
class Solution {
10
10
public:
11
11
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;
27
20
}
28
21
29
- bool kRemaind = true ;
30
- bool getHead = false ;
31
- ListNode *newHead = NULL ;
22
+ ListNode prevhead (0 );
23
+ prevhead.next = head;
32
24
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 ;
48
34
}
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 ;
57
45
}
58
46
}
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 ;
60
59
}
61
- };
60
+ };
You can’t perform that action at this time.
0 commit comments