-
Notifications
You must be signed in to change notification settings - Fork 13
/
Solution061.java
53 lines (44 loc) · 991 Bytes
/
Solution061.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
package algorithm.leetcode;
/**
* @author: mayuan
* @desc: 旋转链表
* @date: 2019/01/03
*/
public class Solution061 {
public ListNode rotateRight(ListNode head, int k) {
if (null == head || 0 > k) {
return null;
}
// 获得链表的长度
int cnt = 0;
ListNode tmp = head;
while (null != tmp) {
++cnt;
tmp = tmp.next;
}
k %= cnt;
if (0 == k) {
return head;
}
ListNode fast = head;
ListNode slow = head;
for (int i = 0; i < k; ++i) {
fast = fast.next;
}
while (null != fast.next) {
fast = fast.next;
slow = slow.next;
}
fast.next = head;
head = slow.next;
slow.next = null;
return head;
}
private class ListNode {
int val;
ListNode next;
ListNode(int x) {
val = x;
}
}
}