- Notifications
You must be signed in to change notification settings - Fork 366
/
Copy pathLeetCode61RotateList.java
42 lines (34 loc) · 1.16 KB
/
LeetCode61RotateList.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
classSolution {
publicListNoderotateRight(ListNodehead, intk) {
if(head == null || head.next == null || k == 0){
returnhead;
}
// calculate the length of the linked list
ListNodecurr = head;
intl = 1;
while(curr.next != null){
l++;
curr = curr.next;
}
//after calculating the length, the current node will be at last node and pointing to null
// therefore point the last node(curr) to the head and make a cycle
curr.next = head;
//in the question k may be a large number and we will be just rotating in the cycle
//therefore to avoid the repeatition we will take the modulo value
k = k % l;
//rotation
//take the remaining length
l = l - k;
//move the curr node to the last node of the rotated list
while(l > 0){
curr = curr.next;
l--;
}
//now the next node will become the head of the new rotated list
head = curr.next;
//and since curr node is last, the next will become null
curr.next = null;
//finally just return the head
returnhead;
}
}