-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathreverse-nodes-in-k-group.c
More file actions
48 lines (40 loc) · 1022 Bytes
/
reverse-nodes-in-k-group.c
File metadata and controls
48 lines (40 loc) · 1022 Bytes
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
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
struct ListNode* reverseKGroup(struct ListNode* head, int k) {
int cnt = 1;
int top = 0;
struct ListNode* stack[k];
struct ListNode* new_head = NULL;
struct ListNode* tail;
struct ListNode* search = head;
while(search){
struct ListNode* next = search->next;
search->next = NULL;
stack[top++] = search;
if(cnt == k){
while(top){
struct ListNode* node = stack[--top];
if(new_head == NULL){
new_head = node;
tail = new_head;
}else{
tail->next = node;
tail = tail->next;
}
}
cnt = 0;
}
cnt++;
search = next;
}
for(int i = 0; i < top; i++){
tail->next = stack[i];
tail = tail->next;
}
return new_head;
}