forked from yuanx/leetcode
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathRotateList.java
More file actions
53 lines (43 loc) · 1.14 KB
/
RotateList.java
File metadata and controls
53 lines (43 loc) · 1.14 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
48
49
50
51
52
53
/**
* Definition for singly-linked list.
* public class ListNode {
* int val;
* ListNode next;
* ListNode(int x) {
* val = x;
* next = null;
* }
* }
*/
public class Solution {
public ListNode rotateRight(ListNode head, int n) {
// Start typing your Java solution below
// DO NOT write main() function
if(head == null || head.next == null) return head;
int count = 0;
ListNode tt = head;
while(tt != null){
count ++;
tt = tt.next;
}
while(n>count)
n = n-count;
if(n==count) return head;
ListNode p = new ListNode(-1);
p.next = head;
head = p;
p= p.next;
ListNode q = p;
for(int i=0; i<n; i++){
q = q.next;
}
while(q.next != null){
q = q.next;
p = p.next;
}
q.next = head.next;
head.next = p.next;
p.next = null;
return head.next;
}
}