【leetcode hot 100 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) {
        ListNode reverse = new ListNode();
        reverse.next = null;
        ListNode curr_reverse=reverse, curr_head = head;

        // 计算链表总数
        int num = 0;
        while(curr_head!=null){
            num++;
            curr_head=curr_head.next;
        }
        int round = num/k; // 可以轮几次

        int n=0;// 现在执行了几个
        while(n<round*k){
            // 新开启一次reverse
            ListNode temp = head.next;
            head.next = null;
            curr_reverse.next = head;
            head = temp;
            n++;
            while((n)%k!=0){
                temp = head.next;
                head.next = curr_reverse.next;
                curr_reverse.next = head;
                head = temp;
                n++;
            }
            // 指向当前轮最后一个
            while(curr_reverse.next != null){
                curr_reverse = curr_reverse.next;
            }
        }
        // 加入后续不需要reverse的节点
        curr_reverse.next = head;
        // 删除头节点
        reverse=reverse.next;
        return reverse;
    }
}

注意:

  • 当新链表个数n<round(轮数)*k时,表示继续置换;否则表示后续节点不需要置换。
  • n%k!=0表示本轮置换还未结束
  • 记得加入后续不需要reverse的节点
  • 设置没有数据的头节点,后续结果要去掉头节点
相关推荐
浅水壁虎1 小时前
vue基础(第二章 )
前端·javascript·vue.js
界面开发小八哥1 小时前
界面控件DevExtreme v26.1新版亮点——支持Angular 22
前端·javascript·angular.js·devexpress·ui开发·devextreme
mONESY2 小时前
React useState 核心原理与最佳实践:从异步更新到性能优化全解
javascript
腻害兔2 小时前
【若依项目-产品经理视角】RuoYi-Vue-Pro 源码拆解:CRM 客户关系模块深度解析——从线索到回款,一套完整的 B2B 销售闭环是怎么搭的?
java·前端·javascript·vue.js·产品经理·ai编程
gis开发之家3 小时前
《Vue3 从入门到大神37篇》Vue3 源码详解(七):watch 与 watchEffect 源码对比——副作用是如何被追踪的?
javascript·前端框架·vue3·vue3源码
bloglin999994 小时前
langchain 和 langgraph 和 react
javascript·react.js·langchain
触底反弹4 小时前
🚀 删了数据刷新又回来?3 组件 × 4 回调 × 3 坑讲透 React 父子通信
前端·javascript·react.js
alphaTao4 小时前
LeetCode 每日一题 2026/7/20-2026/7/26
算法·leetcode
圣保罗的大教堂5 小时前
leetcode 3514. 不同 XOR 三元组的数目 II 中等
leetcode
会周易的程序员6 小时前
js-shm: 高性能 Node.js 共享内存模块
开发语言·javascript·c++·node.js·共享内存·shm