-
Notifications
You must be signed in to change notification settings - Fork 4
/
25. Reverse Nodes in k-Group.java
51 lines (45 loc) · 1.56 KB
/
25. Reverse Nodes in k-Group.java
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
class Solution {
public ListNode reverseKGroup(ListNode head, int k) {
ListNode curr = head;
ListNode prevTail = null;
while (curr != null) {
ListNode first = curr;
ListNode prev = null;
int count = 0;
// Traverse k nodes to reverse
while (curr != null && count < k) {
ListNode next = curr.next;
curr.next = prev;
prev = curr;
curr = next;
count++;
}
// If less than k nodes remain, reverse them back to original order
if (count < k) {
ListNode reverseHead = prev;
prev = null;
while (reverseHead != null) {
ListNode next = reverseHead.next;
reverseHead.next = prev;
prev = reverseHead;
reverseHead = next;
}
if (prevTail == null) {
head = prev;
} else {
prevTail.next = prev;
}
break; // No need to proceed further
}
// Connect the reversed group to the previous tail or update head
if (prevTail == null) {
head = prev;
} else {
prevTail.next = prev;
}
// Update prevTail to the current group's tail
prevTail = first;
}
return head;
}
}