【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的节点
  • 设置没有数据的头节点,后续结果要去掉头节点
相关推荐
语戚2 分钟前
力扣 51. N 皇后:基础回溯、布尔数组优化、位运算全解(Java 实现)
java·算法·leetcode·力扣·剪枝·回溯·位运算
Wect8 分钟前
JS 手撕:对象创建、继承全解析
前端·javascript·面试
py有趣10 分钟前
力扣热门100题之螺旋矩阵
算法·leetcode
3秒一个大13 分钟前
深入理解 JS 中的栈与堆:从内存模型到数据结构,再谈内存泄漏
前端·javascript·数据结构
阿捞231 分钟前
Inertia.js 持久布局实现原理
前端·javascript·html
w2sfot33 分钟前
反AI逆向JS加密
javascript·人工智能·反ai
人道领域40 分钟前
【LeetCode刷题日记】383 赎金信
算法·leetcode·职场和发展
旖-旎1 小时前
哈希表(存在重复元素)(3)
数据结构·c++·学习·算法·leetcode·散列表
Tisfy1 小时前
LeetCode 3740.三个相等元素之间的最小距离 I:今日先暴力,“明日“再哈希
算法·leetcode·哈希算法·题解·模拟·遍历·暴力
东宇科技1 小时前
如何使用js进行抠图。识别商品主体
开发语言·javascript·ecmascript