-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathNo61RotateList.java
More file actions
71 lines (65 loc) · 1.45 KB
/
No61RotateList.java
File metadata and controls
71 lines (65 loc) · 1.45 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
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
package com.wzx.leetcode;
import com.wzx.entity.ListNode;
/**
* @author wzx
* @see <a href="https://leetcode.com/problems/rotate-list/">https://leetcode.com/problems/rotate-list/</a>
*/
public class No61RotateList {
/**
* 直接轮转
* <p>
* time: O(n)
* space: O(1)
*/
public ListNode rotateRight1(ListNode head, int k) {
if (head == null) return null;
// 计算长度
int size = 1;
ListNode tail = head;
while (tail.next != null) {
size++;
tail = tail.next;
}
// 防止重复轮转
k %= size;
// 定位到旋转起始的前一个结点
ListNode preHead = head;
for (int i = 0; i < size - k - 1; i++) {
preHead = preHead.next;
}
// 轮转
tail.next = head;
head = preHead.next;
preHead.next = null;
return head;
}
/**
* 首尾相接成环,再确定头节点
* <p>
* time: O(n)
* space: O(1)
*/
public ListNode rotateRight2(ListNode head, int k) {
if (head == null) return null;
// 计算长度
int size = 1;
ListNode tail = head;
while (tail.next != null) {
size++;
tail = tail.next;
}
// 首尾相接
tail.next = head;
// 防止重复轮转
k %= size;
// 定位到旋转起始的前一个结点
ListNode preHead = head;
for (int i = 0; i < size - k - 1; i++) {
preHead = preHead.next;
}
// 断开
head = preHead.next;
preHead.next = null;
return head;
}
}