-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRotateLinkedList.java
More file actions
33 lines (30 loc) · 898 Bytes
/
RotateLinkedList.java
File metadata and controls
33 lines (30 loc) · 898 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
package swe.LinkedList;
public class RotateLinkedList {
public Node rotateRight(Node head, int k) {
//Input : 1 -> 2 -> 3 -> 4 -> X , k = 2
if (head == null) {
return head;
}
Node tail = head;
int sizeOfTheList = 1;
while (tail.next != null) {
tail = tail.next;
sizeOfTheList++;
}
k = k % sizeOfTheList;
if (k == 0) {
return head;
}
tail.next = head;
int newTailIndex = sizeOfTheList - k;
Node rotatedNewTail = tail;
while (newTailIndex > 0) {
rotatedNewTail = rotatedNewTail.next;
newTailIndex--;
}
Node rotatedNewHead = rotatedNewTail.next;
rotatedNewTail.next = null;
return rotatedNewHead;
//Output: 3 -> 4 -> 1 -> 2 -> X
}
}