-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseNodesInKGroups.java
More file actions
36 lines (30 loc) · 1 KB
/
ReverseNodesInKGroups.java
File metadata and controls
36 lines (30 loc) · 1 KB
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
package LinkedLists;
public class ReverseNodesInKGroups {
public Node reverseKGroup(Node head, int k) {
Node moving = head;
Node temp = new Node(0);
Node ans = null;
while (moving != null) {
// Storing the previous and going forward,
int count = k - 1;
Node prev = moving;
while (moving != null && count > 0) {
moving = moving.next;
count--;
}
// Reversing the k nodes and attaching to temp.
if (moving != null && count == 0) {
Node save = moving.next;
moving.next = null;
Node newHead = ReverseList.reverseList(prev);
temp.next = newHead;
if (ans == null) ans = newHead;
while (temp.next != null) temp = temp.next;
moving = save;
} else {
temp.next = prev;
}
}
return ans == null ? head : ans;
}
}