@@ -16,7 +16,7 @@ public ListNode reverseKGroup(ListNode head, int k) {
16
16
17
17
while (true ) {
18
18
19
- if (index != k ) {
19
+ if (index != k ) { // 查找 k 个节点中的 head 和 tail 节点
20
20
groupTail = groupTail .next ;
21
21
if (groupTail != null ) {
22
22
index ++;
@@ -30,7 +30,8 @@ public ListNode reverseKGroup(ListNode head, int k) {
30
30
return head ;
31
31
}
32
32
}
33
- }else {
33
+ }else {
34
+ // 个数达到 k 时执行交换,返回下一组的 head 节点
34
35
ListNode node = this .swap (groupHead , groupTail );
35
36
if (node == null ) {
36
37
break ;
@@ -45,6 +46,7 @@ public ListNode reverseKGroup(ListNode head, int k) {
45
46
46
47
private ListNode swap (ListNode head , ListNode tail ) {
47
48
49
+ // 反转链表
48
50
ListNode preNode = null ;
49
51
ListNode currentNode = head ;
50
52
while (currentNode != tail ) {
@@ -54,12 +56,17 @@ private ListNode swap(ListNode head, ListNode tail) {
54
56
currentNode = next ;
55
57
}
56
58
59
+ // 当前组的 tail 节点执行 swap
57
60
ListNode node = currentNode .next ;
58
61
currentNode .next = preNode ;
59
62
63
+ // 反转完成,将上一组的 tail 节点指向当前组的 head 节点
64
+ // 第一次反转时上一组 tail 为 null,因此要执行判空操作
60
65
if (this .preGroupTail != null ) {
61
66
this .preGroupTail .next = currentNode ;
62
67
}else {
68
+ // 上一组的 tail 为空说明是第一组执行交换
69
+ // 结果一定是第一组交换后的 head 节点
63
70
result = currentNode ;
64
71
}
65
72
this .preGroupTail = head ;
0 commit comments