-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathReverseByGroupofK.java
More file actions
58 lines (56 loc) · 1.72 KB
/
Copy pathReverseByGroupofK.java
File metadata and controls
58 lines (56 loc) · 1.72 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
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
//reverse the linked list in the group of k
public static Node reverse(Node node, int k)
{
Node previous = null;
Node current = node;
Node next;
Node newHead = null;
Node toBeConnect = null;
while (current != null) {
int i = 0;
// loop to reverse the list upto k length
while (i < k) {
if (current == null)
break;
next = current.next;
current.next = previous;
previous = current;
current = next;
i++;
}
//condition for connecting after the 1st iteration
//Define the new head which will point the head of the new list
if (newHead == null) {
newHead = previous;
}
//Condition for after every other iteration
else {
toBeConnect.next = previous;
}
toBeConnect = node;
node = current;
previous = null;
}
return newHead;
}
// Using recursive approach
public static Node reverse(Node node, int k) {
Node previous = null;
Node current = node;
Node next;
int i = 0;
// loop to reverse the list upto k length
while (i < k) {
if (current.next == null) {
current.next = previous;
return current;
}
next = current.next;
current.next = previous;
previous = current;
current = next;
i++;
}
node.next = reverse(current, k);
return previous;
}