forked from client69/Open
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateLinkedList.java
More file actions
40 lines (29 loc) · 953 Bytes
/
RotateLinkedList.java
File metadata and controls
40 lines (29 loc) · 953 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
package linkedlists;
public class RotateLinkedList {
public class ListNode {
int val;
ListNode next;
ListNode() {}
ListNode(int val) { this.val = val; }
ListNode(int val, ListNode next) { this.val = val; this.next = next; }
}
public static ListNode rotateRight(ListNode head, int k) {
if(k ==0) return head;
int size = 1;
ListNode fast = head;
ListNode slow = head;
while(fast.next != null){
size++;
fast = fast.next;
}
//slow points to the item where the cycle starts
// use to break cycle later on
for(int cycle = size - k % size; cycle > 1; cycle--){
slow = slow.next;
}
fast.next = head;
head = slow.next;
slow.next = null;
return head;
}
}