-
Notifications
You must be signed in to change notification settings - Fork 119
/
Copy pathReverse Nodes in Even Length Groups.cpp
61 lines (52 loc) · 1.75 KB
/
Reverse Nodes in Even Length Groups.cpp
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
61
// Runtime: 2456 ms (Top 6.39%) | Memory: 329.7 MB (Top 84.60%)
class Solution {
public:
// Function to reverse a linked list
ListNode* reverseList(ListNode* head) {
if(!head)
return head;
ListNode* prev = NULL;
while(head) {
ListNode* temp = head -> next;
head -> next = prev;
prev = head;
head = temp;
}
return prev;
}
ListNode* reverseEvenLengthGroups(ListNode* head) {
// Creating a dummy node to avoid adding checks for the first node
ListNode* dummy = new ListNode();
dummy -> next = head;
ListNode* prev = dummy;
// Loop to determine the lengths of groups
for(int len = 1; len < 1e5 && head; len++) {
ListNode* tail = head;
ListNode* nextHead;
// Determining the length of the current group
// Its maximum length can be equal to len
int j = 1;
while(j < len && tail && tail -> next) {
tail = tail -> next;
j++;
}
// Head of the next group
nextHead = tail -> next;
if((j % 2) == 0) {
// If even sized group is found
// Reversing the group and setting prev and head appropriately
tail -> next = NULL;
prev -> next = reverseList(head);
prev = head;
head -> next = nextHead;
head = nextHead;
} else {
// If group is odd sized, then simply going towards the next group
prev = tail;
head = nextHead;
}
}
// Returning the head
return dummy -> next;
}
};