-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateList.java
More file actions
34 lines (34 loc) · 846 Bytes
/
RotateList.java
File metadata and controls
34 lines (34 loc) · 846 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
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class RotateList {
public ListNode rotateRight(ListNode head, int n) {
if(head == null) return head;
ListNode nil = new ListNode(-1);
nil.next = head;
ListNode tmp = head;
int cnt = 0, len = 0;
while(cnt++ < n){
tmp = tmp.next;
if(tmp == null && len == 0){
len = cnt;n %= len;cnt = 0;tmp = head;
}
}
while(tmp != null && tmp.next != null){
head = head.next;
tmp = tmp.next;
}
tmp.next = nil.next;
nil.next = head.next;
head.next = null;
return nil.next;
}
}