-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseInGroupsOfSizeK.java
More file actions
45 lines (38 loc) · 1010 Bytes
/
ReverseInGroupsOfSizeK.java
File metadata and controls
45 lines (38 loc) · 1010 Bytes
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
package DoublyLinkedList;
/**
* V. Important Question.
* */
public class ReverseInGroupsOfSizeK {
static Node revListInGroupOfGivenSize(Node head, int k) {
if (head == null) return head;
Node st = head;
Node tail = null;
Node ans = null;
while (st != null) {
int count = 1;
Node curr = st;
Node prev = null;
Node next;
// Reversing the k nodes.
while (curr != null && count <= k) {
next = curr.next;
curr.prev = next;
curr.next = prev;
prev = curr;
curr = next;
count++;
}
if (ans == null) {
ans = prev;
ans.prev = null;
}
if (tail != null) {
tail.next = prev;
prev.prev = tail;
}
tail = st;
st = curr;
}
return ans;
}
}