【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的节点
  • 设置没有数据的头节点,后续结果要去掉头节点
相关推荐
代码不加糖3 分钟前
MessageChannel是什么,有什么使用场景?
前端·javascript
人无远虑必有近忧!30 分钟前
fetch请求图片报跨域
前端·javascript
风筝在晴天搁浅42 分钟前
LeetCode CodeTop 82.删除排序链表中的重复元素Ⅱ
算法·leetcode·链表
不会就选b1 小时前
数据结构之链表OJ题(下)
数据结构·链表
chushiyunen1 小时前
vue export default
前端·javascript·vue.js
洛水水1 小时前
【力扣100题】84.字符串解码
算法·leetcode·职场和发展
zzqssliu1 小时前
Next.js图片自适应压缩:跨境站点图片加载提速代码方案
linux·javascript·ubuntu
洛水水1 小时前
【力扣100题】89.下一个排列
数据结构·算法·leetcode
洛水水1 小时前
【力扣100题】90.寻找重复数
算法·leetcode·职场和发展
alphaTao2 小时前
LeetCode 每日一题 2026/6/8-2026/6/14
算法·leetcode