Skip to content

Commit 6083701

Browse files
committed
001 号第一周作业: LeetCode25- Reverse Nodes in k-Group
1 parent 2dbbeac commit 6083701

File tree

1 file changed

+9
-2
lines changed

1 file changed

+9
-2
lines changed

Week_01/id_1/LeetCode25.java

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -16,7 +16,7 @@ public ListNode reverseKGroup(ListNode head, int k) {
1616

1717
while (true) {
1818

19-
if (index != k) {
19+
if (index != k) { // 查找 k 个节点中的 head 和 tail 节点
2020
groupTail = groupTail.next;
2121
if (groupTail != null) {
2222
index ++;
@@ -30,7 +30,8 @@ public ListNode reverseKGroup(ListNode head, int k) {
3030
return head;
3131
}
3232
}
33-
}else {
33+
}else {
34+
// 个数达到 k 时执行交换,返回下一组的 head 节点
3435
ListNode node = this.swap(groupHead, groupTail);
3536
if (node == null) {
3637
break;
@@ -45,6 +46,7 @@ public ListNode reverseKGroup(ListNode head, int k) {
4546

4647
private ListNode swap(ListNode head, ListNode tail) {
4748

49+
// 反转链表
4850
ListNode preNode = null;
4951
ListNode currentNode = head;
5052
while (currentNode != tail) {
@@ -54,12 +56,17 @@ private ListNode swap(ListNode head, ListNode tail) {
5456
currentNode = next;
5557
}
5658

59+
// 当前组的 tail 节点执行 swap
5760
ListNode node= currentNode.next;
5861
currentNode.next = preNode;
5962

63+
// 反转完成,将上一组的 tail 节点指向当前组的 head 节点
64+
// 第一次反转时上一组 tail 为 null,因此要执行判空操作
6065
if (this.preGroupTail != null) {
6166
this.preGroupTail.next = currentNode;
6267
}else {
68+
// 上一组的 tail 为空说明是第一组执行交换
69+
// 结果一定是第一组交换后的 head 节点
6370
result = currentNode;
6471
}
6572
this.preGroupTail = head;

0 commit comments

Comments
 (0)