-
Notifications
You must be signed in to change notification settings - Fork 14
/
Solution92.java
60 lines (48 loc) · 1.38 KB
/
Solution92.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
55
56
57
58
59
60
package leetcode.linkedlist;
import leetcode.ListNode;
public class Solution92 {
public ListNode reverseBetween(ListNode head, int left, int right) {
if (left == right) {
return head;
}
// 找到 right 节点和它的后继节点
ListNode rightNode = head;
while (right != 1) {
right--;
rightNode = rightNode.next;
}
ListNode tail = rightNode.next;
// 断开链接
rightNode.next = null;
// 找到 left 节点和它的前驱节点
ListNode leftNode = head;
if (left == 1) {
ListNode newHead = reverse(head);
head.next = tail;
return newHead;
} else {
ListNode pre = new ListNode(-1);
pre.next = head;
while (left > 1) {
left--;
leftNode = leftNode.next;
pre = pre.next;
}
// 反转并链接
ListNode reverseNode = reverse(leftNode);
pre.next = reverseNode;
leftNode.next = tail;
return head;
}
}
private ListNode reverse(ListNode node) {
ListNode pre = null;
while (node != null) {
ListNode temp = node.next;
node.next = pre;
pre = node;
node = temp;
}
return pre;
}
}