8.23 第一次做,无法 AC
8.24 可以一次 AC
第一次复习
9.8 无法 AC
9.14 无法 AC
9.15 可以 AC,就是还是有点粗心的地方
题目描述
力扣:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/submissions/
解题思路
题解:https://leetcode-cn.com/problems/reverse-nodes-in-k-group/solution/
9.8 感悟:
下面第 16 行要记得写!!!!
第 12 行的 end.next 和第 16、20 行的 end != null 或 end == null 没有任何关系;
- 第 12 行的 end.next != null 是判断是否需要进行下一趟遍历 K 个节点;
- 而第 16、20 行的 end != null 或 end == null 是用来判断是否不足 K 个节点能够遍历而提前退出。
9.15 感悟:
下面第 29 和 31 行代码一定得等于 start 节点,不能等于 end 节点,end 节点反转链表后已经到前面去了!!
class Solution {public ListNode reverseKGroup(ListNode head, int k) {ListNode sentry = new ListNode(0);sentry.next = head;ListNode pre = sentry;ListNode end = sentry;// end.next != null 判断是否有节点能够继续开始下一趟 K 次遍历// 确实,得要 end.next != null,才有必要往前遍历 K 个节点,然后才能够反转链表while(end.next != null) {for(int i = 0; i < k; i++) {// end != null 判断是否不足 K 个节点而提前退出遍历if(end != null) end = end.next;}// end == null 就代表上面的 for 循环提前退出了,不足 K 个节点if(end == null) break;ListNode next = end.next; // 暂存 K 个一组链表的下一个节点,以便接回来end.next = null; // 断开 K 个一组链表与下一个节点的连接,以便反转链表成功ListNode start = pre.next; // 记录 K 个一组链表的头,以便传入反转方法进行反转pre.next = reverseList(start); // 返回反转链表后的头节点并将其接在 pre 后面start.next = next; // 刚刚的【头】反转后变成了尾节点,用其与原链表拼接起来pre = start; // 重置 preend = start; // 重置 end}return sentry.next;}public ListNode reverseList(ListNode head) {ListNode pre = null, cur = head;while(cur != null) {ListNode tmp = cur.next;cur.next = pre;pre = cur;cur = tmp;}return pre;}}
