-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLeetcode061.java
54 lines (43 loc) · 1.13 KB
/
Leetcode061.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
43
44
45
46
47
48
49
50
51
52
53
54
package test;
public class Leetcode061 {
public ListNode rotateRight(ListNode head, int k) {
ListNode newhead = head;
ListNode cur = head;
ListNode pre = head;
int count = 0;
if (head == null || head.next == null)
return head;
while (cur != null) {
count++;
cur = cur.next;
}
k = k % count;
cur = head;
if (k == 0)
return head;
for (int i=k; i>1; i--) {
if (cur == null || cur.next == null)
return head;
cur = cur.next;
}
if (cur == null || cur.next == null)
return head;
else {
cur = cur.next;
newhead = newhead.next;
}
while (cur.next != null) {
newhead = newhead.next;
pre = pre.next;
cur = cur.next;
}
cur.next = head;
pre.next = null;
return newhead;
}
}
class ListNode {
int val;
ListNode next;
ListNode(int x) { val = x; }
}