[Geeks for Geeks] Reverse a Linked List in groups of given size

Reverse a Linked List in groups of given size

Given a linked list of size N. The task is to reverse every k nodes (where k is an input to the function) in the linked list. If the number of nodes is not a multiple of k then left-out nodes, in the end, should be considered as a group and must be reversed (See Example 2 for clarification).

  • Time : O(n)
  • Space : O(1)
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
struct NodeWrapper {
node* head;
node* tail;
node* nextHead;
bool succeed;

};

class Solution {
NodeWrapper _reverse(node* head, int k) {
node* dummy = new node(-1);
node* tail = head;
while(k-- and head) {
node* tmp = head->next;
head->next = dummy->next;
dummy->next = head;
head = tmp;
}

return {dummy->next, tail, head, k == -1};
}
public:
struct node *reverse(struct node *head, int k) {
node* dummy = new node(-1);
node* dummyTail = dummy;
while(head) {
NodeWrapper wrapper = _reverse(head, k);

dummyTail->next = wrapper.head;
dummyTail = wrapper.tail;
head = wrapper.nextHead;

}
return dummy->next;
}
};
Author: Song Hayoung
Link: https://songhayoung.github.io/2022/05/17/PS/GeeksforGeeks/reverse-a-linked-list-in-groups-of-given-size/
Copyright Notice: All articles in this blog are licensed under CC BY-NC-SA 4.0 unless stating additionally.