25. K 个一组翻转链表

题解参考:https://leetcode.cn/problems/reverse-nodes-in-k-group/solutions/10416/tu-jie-kge-yi-zu-fan-zhuan-lian-biao-by-user7208t/


设置dummy虚拟头节点,pre为待翻转部分的前驱(用于连接),end为待翻转部分中的结尾节点(用k定),next为待翻转部分的后续节点(用于连接),bg为翻转前的翻转部分的开始节点,进入reverse后,会有cur节点作为副本,因此bg的位置不会变,翻转后,bg所在节点变成了结尾,将其和next相连,reverse返回的节点(新开始节点)和pre相连。
pre指向bg,作为下一个待翻转部分的前驱。
end指向pre,从pre出发数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) {
        ListNode dummy = new ListNode(0, head);
        ListNode pre = dummy, end = dummy;
        while (end.next != null) {
            for (int i = 0; i < k && end != null; ++i) end = end.next; 
            // 注意只要访问next节点,就要检查这个节点是否为空
            if (end == null) break;
            ListNode bg = pre.next;
            ListNode nxt = end.next;
            end.next = null;
            pre.next = reverse(bg);
            bg.next = nxt;
            pre = bg;
            end = pre;
        }
        return dummy.next;
    }
    private ListNode reverse(ListNode head) { 
        ListNode pre = null;
        ListNode cur = head;
        while (cur != null) {
            ListNode nxt = cur.next;
            cur.next = pre;
            pre = cur;
            cur = nxt;
        }
        return pre;
    }
}
相关推荐
nongcunqq1 小时前
abap 操作 excel
java·数据库·excel
R-G-B2 小时前
【02】C#入门到精通——C# 变量、输入/输出、类型转换
开发语言·c#·c# 变量·c#输入/输出·c#类型转换
星河队长2 小时前
C# 软件加密方法,有使用时间限制,同时要防止拷贝
开发语言·c#
史迪奇_xxx2 小时前
10、一个简易 vector:C++ 模板与 STL
java·开发语言·c++
2301_801252222 小时前
Java中的反射
java·开发语言
Kiri霧2 小时前
Rust开发环境搭建
开发语言·后端·rust
weixin-a153003083162 小时前
[数据抓取-1]beautifulsoup
开发语言·python·beautifulsoup
我不是QI3 小时前
DES 加密算法:核心组件、加解密流程与安全特性
经验分享·算法·安全·网络安全·密码学
遇印记3 小时前
大二java学习笔记:二维数组
java·笔记·学习
前端小刘哥3 小时前
新版视频直播点播EasyDSS平台,让跨团队沟通高效又顺畅
算法