Leetcode面试经典150题-25.K个一组反转链表

解法都在代码里,不懂就留言或者私信

java 复制代码
/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode() {}
 *     ListNode(int val) { this.val = val; }
 *     ListNode(int val, ListNode next) { this.val = val; this.next = next; }
 * }
 */
class Solution {
    public ListNode reverseKGroup(ListNode head, int k) {
        /**1个1组反转吗?神经病啊 */
        if(k == 1) {
            return head;
        }
        /**题目已经给出k<=n了,所以无需验证k是否大于长度*/
        int count = 0;
        ListNode cur = head;
        /**当前区间的头 */
        ListNode curHead = head;
        /**反转之后链表的头 */
        ListNode newHead = null;
        /**上个区间反转之后的结尾 */
        ListNode preLast = null;
        /**下一个节点用于遍历 */
        ListNode next = null;
        while(cur != null) {
            /**路过节点就统计,而不是走一步统计,这样比较方便 */
            count ++;
            /**拿到当前的下个节点,因为cur的next指针会发生变化,所以需要提前拿到 */
            next = cur.next;
            /**如果够了k个 */
            if(count == k) {
                /**断开和后面的连接,方便当前区间的反转 */
                cur.next = null;
                /**反转当前区间 */
                ListNode curHeadReverse = reverse(curHead);
                /**如果前一个区间的尾巴不为空(当前不是第一个区间) */
                if(preLast != null) {
                    preLast.next = curHeadReverse;
                }
                /**如果新的头为空(当前是第一个区间),给新的头赋值 */
                if(newHead == null) {
                    newHead = curHeadReverse;
                }
                /**preLast是给下个区间用的,它的next指向下个区间反转之后的头 */
                preLast = curHead;
                /**当前区间的尾巴指向下个区间目前的头(反转之前的) */
                curHead.next = next;
                /**下个区间的头*/
                curHead = next;
                /**当前k个结束,count归0 */
                count = 0;
            }
            cur = next;
        }
        return newHead;
    }
    /**经典的反转链表的题 */
    public ListNode reverse(ListNode head) {
        ListNode cur = head;
        ListNode pre = null;
        ListNode next = null;
        while(cur != null) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        return pre;
    }
}

运行结果

肯定是最优解了,但是其中的遍历可以删除一点,其实无所谓的

相关推荐
石小石Orz3 分钟前
AI 正在蚕食我们的编码能力
前端·后端·算法
民乐团扒谱机2 小时前
【微实验】NSGA-II(非支配排序遗传算法)——解决多目标优化问题的“自然选择模拟器”
linux·人工智能·算法
青少儿编程课堂2 小时前
蓝桥杯·全国青少年信息素养大赛·电子学会Python/C++考级:中缀表达式求值解析
c++·python·算法·bfs·信息学竞赛
文丑颜不良啊2 小时前
LeetCode2261~2280题目解析
java·leetcode
武子康4 小时前
Qwen-Drive 到底是什么:4B 级 VLM 如何成为驾驶策略底座
人工智能·算法·机器学习
zh_xuan5 小时前
LeeCode 496. 下一个更大元素I
数据结构·算法·栈·单调栈
机 _ 长5 小时前
05 智算运维|8 张卡怎么才算「捆成一张」:NCCL 实测与拓扑
运维·人工智能·算法·智算运维
早起CaiCai6 小时前
【2023-01 OM】利用深度学习算法融合异质观测实现海洋场降尺度
人工智能·深度学习·算法
梦里寻码7 小时前
我用 NestJS + Vue3 写了一套完整的研发管理系统(58 表 / 229 API / 130 项断言,全开源
前端·后端·算法
猿人谷7 小时前
Surrogate Model:让进化算法学会“预测”,为什么它正在成为智能优化的重要技术?
后端·算法·架构