【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的节点
  • 设置没有数据的头节点,后续结果要去掉头节点
相关推荐
Miraitowa_cheems16 分钟前
LeetCode算法日记 - Day 108: 01背包
数据结构·算法·leetcode·深度优先·动态规划
JohnYan23 分钟前
Bun技术评估 - 30 SSE支持
javascript·后端·bun
yzx99101332 分钟前
一个嵌入式存储芯片质量评估系统的网页界面设计
开发语言·javascript·ecmascript
fruge1 小时前
前端可视化家庭账单:用 ECharts 实现支出统计与趋势分析
前端·javascript·echarts
小武~1 小时前
Leetcode 每日一题C 语言版 -- 88 merge sorted array
c语言·算法·leetcode
荔枝吖1 小时前
html2canvas+pdfjs 打印html
前端·javascript·html
起名时在学Aiifox2 小时前
深入解析 Electron 打包中的 EPERM: operation not permitted 错误
前端·javascript·electron
hachi03132 小时前
Vue中input disabled时点击事件不触发怎么办?
javascript·vue.js·ecmascript
漫天黄叶远飞3 小时前
别再把对象当“字典”!JS 零基础也能看懂的“属性账本”拆解笔记
javascript
起名时在学Aiifox3 小时前
Vue3 + Element Plus 表格排序实战:基于状态字段的智能排序方案
前端·javascript·vue.js·element plus