Skip to content

Commit 1867dd7

Browse files
committed
25.K个一组翻转链表
1 parent 94c07ef commit 1867dd7

File tree

2 files changed

+79
-0
lines changed

2 files changed

+79
-0
lines changed

leetcode_Java/DoneTitle.txt

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,7 @@
1010
20. 有效的括号
1111
21. 合并两个有序链表
1212
22. 括号生成
13+
25. K 个一组翻转链表
1314
31. 下一个排列
1415
37. 解数独
1516
39. 组合总和

leetcode_Java/Solution0025.java

Lines changed: 78 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,78 @@
1+
// 25. K 个一组翻转链表
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+
1、指针含义
18+
1)root:哨兵节点
19+
2)pre:上一组链表的尾节点
20+
3)start:当前组链表的头节点
21+
4)end:当前组链表的尾节点
22+
5)next:下一组链表的头节点
23+
2、当有下一组时,遍历k次找到新的当前组的尾节点end,如果不足k个节点则结束
24+
3、标记下一组的头节点next,用于后续与上一组连接
25+
4、标记当前组的头节点start,尾节点下一指针指向空,使得当前组链表独立
26+
5、当前组链表反转,返回新的头节点,上一组链表的尾节点pre连接当前组新的头节点end,新的尾节点start连接下一组的头节点next
27+
6、重新初始化指针指向,pre、end指向start,准备下一轮处理
28+
29+
0 → 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8
30+
root/pre/end
31+
=============================================================
32+
0 → 1 → 2 → 3 → 4 → 5 → 6 → 7 → 8
33+
root/pre end
34+
=============================================================
35+
0 → 1 → 2 → 3 4 → 5 → 6 → 7 → 8
36+
root/pre start end next
37+
=============================================================
38+
0 → 3 → 2 → 1 → 4 → 5 → 6 → 7 → 8
39+
root/pre end start next
40+
=============================================================
41+
0 → 3 → 2 → 1 → 4 → 5 → 6 → 7 → 8
42+
root pre/end/start next
43+
*/
44+
class Solution {
45+
public ListNode reverseKGroup(ListNode head, int k) {
46+
ListNode root = new ListNode(0, head);
47+
ListNode pre = root;
48+
ListNode end = root;
49+
while (end.next != null) {
50+
for (int i = 0; i < k && end != null; i++) {
51+
end = end.next;
52+
}
53+
if (end == null) {
54+
break;
55+
}
56+
ListNode next = end.next;
57+
ListNode start = pre.next;
58+
end.next = null;
59+
pre.next = reverse(start);
60+
start.next = next;
61+
pre = start;
62+
end = start;
63+
}
64+
return root.next;
65+
}
66+
67+
// 206.反转链表
68+
private ListNode reverse(ListNode head) {
69+
ListNode before = null, after;
70+
while (head != null) {
71+
after = head.next;
72+
head.next = before;
73+
before = head;
74+
head = after;
75+
}
76+
return before;
77+
}
78+
}

0 commit comments

Comments
 (0)