-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateList.java
More file actions
47 lines (42 loc) · 1.09 KB
/
RotateList.java
File metadata and controls
47 lines (42 loc) · 1.09 KB
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
43
44
45
46
47
/**
* 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) {
ListNode newHead = new ListNode(-1);
if(head == null || n<1) return head;
newHead.next = head;
ListNode prev = newHead;
int len = 1;
for(;len<n;len++) {
if(head.next!=null)head = head.next;
else break;
}
if(len == n && head.next == null)
return newHead.next;
else if(len<n) {
n %= len;
n = len - n;
for(int i=0; i<n; i++) {
prev = prev.next;
}
} else {
while(head.next!=null) {
head = head.next;
prev = prev.next;
}
}
head.next = newHead.next;
newHead.next = prev.next;
prev.next = null;
return newHead.next;
}
}