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;
    }
}
相关推荐
Rhys..4 分钟前
Python&Flask 使用 DBUtils 创建通用连接池
开发语言·python·mysql
土了个豆子的15 分钟前
04.事件中心模块
开发语言·前端·visualstudio·单例模式·c#
老华带你飞34 分钟前
考研论坛平台|考研论坛小程序系统|基于java和微信小程序的考研论坛平台小程序设计与实现(源码+数据库+文档)
java·vue.js·spring boot·考研·小程序·毕设·考研论坛平台小程序
和光同尘@35 分钟前
66. 加一 (编程基础0到1)(Leetcode)
数据结构·人工智能·算法·leetcode·职场和发展
CHEN5_0235 分钟前
leetcode-hot100 11.盛水最多容器
java·算法·leetcode
songx_9939 分钟前
leetcode18(无重复字符的最长子串)
java·算法·leetcode
@菜菜_达41 分钟前
Lodash方法总结
开发语言·前端·javascript
GISer_Jing1 小时前
低代码拖拽实现与bpmn-js详解
开发语言·javascript·低代码
@areok@1 小时前
C++mat传入C#OpencvCSharp的mat
开发语言·c++·opencv·c#
小王C语言1 小时前
【C++进阶】---- map和set的使用
开发语言·c++