-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrotateList.java
More file actions
28 lines (24 loc) · 766 Bytes
/
rotateList.java
File metadata and controls
28 lines (24 loc) · 766 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
class Solution {
public ListNode rotateRight(ListNode head, int k) {
if(head == null)
return null;
ListNode tail = head;
int n = 1;
while (tail.next != null) {
++n ;
tail = tail .next ;
}
k = k%n; //if the length of k is larger, we are just doing the mod and reducing cycles.
if(k==0) return head;
int stepsToNewHead = n - k;
tail.next = head;
//making the list as cycle.
ListNode newTail = tail;
while (stepsToNewHead-- > 0) {
newTail = newTail .next ; }
ListNode newHead = newTail.next;
newTail.next = null;
return newHead;
}
}
//actually easy