forked from neetcode-gh/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy path0025-reverse-nodes-in-k-group.c
60 lines (47 loc) · 1.26 KB
/
0025-reverse-nodes-in-k-group.c
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
50
51
52
53
54
55
56
57
58
59
60
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* struct ListNode *next;
* };
*/
typedef struct ListNode ListNode;
ListNode* getKth(ListNode* curr, int k)
{
while(curr && k > 0)
{
curr = curr->next;
k--;
}
return curr;
}
struct ListNode* reverseKGroup(struct ListNode* head, int k){
ListNode dummy = { 0, head };
ListNode* prevGroupTail = &dummy;
while(true)
{
ListNode* kth = getKth(prevGroupTail, k);
if(!kth)
{
break;
}
ListNode* nextGroupHead = kth->next;
// Reverse group
ListNode* prev = nextGroupHead;
ListNode* curr = prevGroupTail->next;
while(curr != nextGroupHead)
{
ListNode* temp = curr->next;
curr->next = prev;
// Increment the pointers
prev = curr;
curr = temp;
}
ListNode* lastNodeInCurrentGroup = prevGroupTail->next;
// Connect the previous group to the current group
prevGroupTail->next = kth; // kth is now the first node in the group
// Update prevGroupTail for the next iteration of the loop
prevGroupTail = lastNodeInCurrentGroup;
}
return dummy.next;
}