Skip to content

Commit c71eec7

Browse files
committed
92.反转链表II
1 parent f2eb7f8 commit c71eec7

File tree

3 files changed

+71
-0
lines changed

3 files changed

+71
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@
3131
84. 柱状图中最大的矩形
3232
88. 合并两个有序数组
3333
90. 子集 II
34+
92. 反转链表 II
3435
93. 复原 IP 地址
3536
94. 二叉树的中序遍历
3637
101. 对称二叉树

leetcode_Java/Solution0025.java

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@
1414

1515

1616
/*
17+
“92.反转链表II”是只反转一次,逻辑相似
1718
1、指针含义
1819
1)root:哨兵节点
1920
2)pre:上一组链表的尾节点

leetcode_Java/Solution0092.java

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,69 @@
1+
// 92. 反转链表 II
2+
3+
4+
/**
5+
* Definition for singly-linked list.
6+
* public class ListNode {
7+
* int val;
8+
* ListNode next;
9+
* ListNode() {}
10+
* ListNode(int val) { this.val = val; }
11+
* ListNode(int val, ListNode next) { this.val = val; this.next = next; }
12+
* }
13+
*/
14+
15+
16+
/*
17+
“25.K个一组翻转链表”是反转多次,逻辑相似
18+
1、指针含义
19+
1)root:哨兵节点
20+
2)pre:反转区域前的尾节点
21+
3)start:反转区域的头节点
22+
4)end:反转区域的尾节点
23+
5)next:反转区域后的头节点
24+
2、pre、end根据给定的区域范围走到指定位置,标记start、next
25+
3、end下一指针指向空,使得反转区域链表独立
26+
4、反转区域链表反转,返回新的头节点,pre连接新的头节点end,新的尾节点连接next
27+
28+
0 → 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8
29+
root/pre/end
30+
=============================================================
31+
0 → 1 → 2 → 3 → 4 → 5 6 → 7 → 8
32+
root pre start end next
33+
=============================================================
34+
0 → 1 → 2 → 5 → 4 → 3 → 6 → 7 → 8
35+
root pre end start next
36+
*/
37+
class Solution {
38+
public ListNode reverseBetween(ListNode head, int left, int right) {
39+
if (left == right) {
40+
return head;
41+
}
42+
ListNode root = new ListNode(0, head);
43+
ListNode pre = root, end = root, start, next;
44+
for (int i = 1; i < left; i++) {
45+
pre = pre.next;
46+
}
47+
for (int i = 0; i < right; i++) {
48+
end = end.next;
49+
}
50+
next = end.next;
51+
start = pre.next;
52+
end.next = null;
53+
pre.next = reverse(start);
54+
start.next = next;
55+
return root.next;
56+
}
57+
58+
// 206.反转链表
59+
private ListNode reverse(ListNode head) {
60+
ListNode before = null, after;
61+
while (head != null) {
62+
after = head.next;
63+
head.next = before;
64+
before = head;
65+
head = after;
66+
}
67+
return before;
68+
}
69+
}

0 commit comments

Comments
 (0)