Skip to content

Commit 2d7db2e

Browse files
authoredNov 7, 2024
Reverse Alternate K group nodes
1 parent 7b48d1e commit 2d7db2e

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed
 
+42
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
//reverse alternate k group nodes in LL
2+
// https://www.geeksforgeeks.org/reverse-alternate-k-nodes-in-a-singly-linked-list/
3+
public ListNode reverseAlternateKGroup(ListNode head, int k) {
4+
if (k <= 1 || head == null) {
5+
return head;
6+
}
7+
8+
// skip the first left-1 nodes
9+
ListNode current = head;
10+
ListNode prev = null;
11+
12+
while (current != null) {
13+
ListNode last = prev;
14+
ListNode newEnd = current;
15+
16+
// reverse between left and right
17+
ListNode next = current.next;
18+
for (int i = 0; current != null && i < k; i++) {
19+
current.next = prev;
20+
prev = current;
21+
current = next;
22+
if (next != null) {
23+
next = next.next;
24+
}
25+
}
26+
27+
if (last != null) {
28+
last.next = prev;
29+
} else {
30+
head = prev;
31+
}
32+
33+
newEnd.next = current;
34+
35+
// skip the k nodes
36+
for (int i = 0; current != null && i < k; i++) {
37+
prev = current;
38+
current = current.next;
39+
}
40+
}
41+
return head;
42+
}

0 commit comments

Comments
 (0)