-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathReverseEveryKElements.java
67 lines (57 loc) · 2.24 KB
/
ReverseEveryKElements.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
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
import java.util.*;
//class ListNode {
// int value = 0;
// ListNode next;
//
// ListNode(int value) {
// this.value = value;
// }
//}
class ReverseEveryKElements {
public static ListNode reverse(ListNode head, int k) {
if (k <= 1 || head == null)
return head;
ListNode current = head, previous = null;
while (true) {
ListNode lastNodeOfPreviousPart = previous;
// after reversing the LinkedList 'current' will become the last node of the sub-list
ListNode lastNodeOfSubList = current;
ListNode next = null; // will be used to temporarily store the next node
// reverse 'k' nodes
for (int i = 0; current != null && i < k; i++) {
next = current.next;
current.next = previous;
previous = current;
current = next;
}
// connect with the previous part
if (lastNodeOfPreviousPart != null)
lastNodeOfPreviousPart.next = previous; // 'previous' is now the first node of the sub-list
else // this means we are changing the first node (head) of the LinkedList
head = previous;
// connect with the next part
lastNodeOfSubList.next = current;
if (current == null) // break, if we've reached the end of the LinkedList
break;
// prepare for the next sub-list
previous = lastNodeOfSubList;
}
return head;
}
public static void main(String[] args) {
ListNode head = new ListNode(1);
head.next = new ListNode(2);
head.next.next = new ListNode(3);
head.next.next.next = new ListNode(4);
head.next.next.next.next = new ListNode(5);
head.next.next.next.next.next = new ListNode(6);
head.next.next.next.next.next.next = new ListNode(7);
head.next.next.next.next.next.next.next = new ListNode(8);
ListNode result = ReverseEveryKElements.reverse(head, 3);
System.out.print("Nodes of the reversed LinkedList are: ");
while (result != null) {
System.out.print(result.value + " ");
result = result.next;
}
}
}