-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRotateLinkedList.java
More file actions
54 lines (45 loc) · 1.7 KB
/
RotateLinkedList.java
File metadata and controls
54 lines (45 loc) · 1.7 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
import java.util.*;
class ListNode {
int value = 0;
ListNode next;
ListNode(int value) {
this.value = value;
}
}
class RotateLinkedList {
public static ListNode rotate(ListNode head, int rotations) {
if (head == null || head.next == null || rotations <= 0)
return head;
// find the length and the last node of the list
ListNode lastNode = head;
int listLength = 1;
while (lastNode.next != null) {
lastNode = lastNode.next;
listLength++;
}
lastNode.next = head; // connect the last node with the head to make it a circular list
rotations %= listLength; // no need to do rotations more than the length of the list
int skipLength = listLength - rotations;
ListNode lastNodeOfRotatedList = head;
for (int i = 0; i < skipLength - 1; i++)
lastNodeOfRotatedList = lastNodeOfRotatedList.next;
// 'lastNodeOfRotatedList.next' is pointing to the sub-list of 'k' ending nodes
head = lastNodeOfRotatedList.next;
lastNodeOfRotatedList.next = null;
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);
ListNode result = RotateLinkedList.rotate(head, 3);
System.out.print("Nodes of the reversed LinkedList are: ");
while (result != null) {
System.out.print(result.value + " ");
result = result.next;
}
}
}