【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的节点
  • 设置没有数据的头节点,后续结果要去掉头节点
相关推荐
Moment6 小时前
富文本编辑器在 AI 时代为什么这么受欢迎
前端·javascript·后端
爱敲代码的小鱼7 小时前
AJAX(异步交互的技术来实现从服务端中获取数据):
前端·javascript·ajax
月挽清风7 小时前
代码随想录第十五天
数据结构·算法·leetcode
铅笔侠_小龙虾9 小时前
Flutter 实战: 计算器
开发语言·javascript·flutter
TracyCoder1239 小时前
LeetCode Hot100(34/100)——98. 验证二叉搜索树
算法·leetcode
大模型玩家七七9 小时前
梯度累积真的省显存吗?它换走的是什么成本
java·javascript·数据库·人工智能·深度学习
2501_944711439 小时前
JS 对象遍历全解析
开发语言·前端·javascript
发现一只大呆瓜10 小时前
虚拟列表:支持“向上加载”的历史消息(Vue 3 & React 双版本)
前端·javascript·面试
阔皮大师10 小时前
INote轻量文本编辑器
java·javascript·python·c#
lbb 小魔仙10 小时前
【HarmonyOS实战】React Native 表单实战:自定义 useReactHookForm 高性能验证
javascript·react native·react.js