LeetCode:148排序链表

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 sortList(ListNode head) {
        if(head == null || head.next == null){
            return head;
        }

        //计算总长度
        int length = 0;
        ListNode node = head;
        while(node != null){
            length++;
            node = node.next;
        }

        ListNode dummy = new ListNode(0);
        dummy.next = head;

        //步长从1开始,依次翻倍
        for(int subLength = 1; subLength < length; subLength *= 2){
            ListNode prev = dummy;
            ListNode curr = dummy.next;
            
            while(curr != null){
                //切第一段
                ListNode head1 = curr;
                for(int i = 1; i < subLength && curr.next != null; i++){
                    curr = curr.next;
                }
                //切第二段
                ListNode head2 = curr.next;
                curr.next = null;
                curr = head2;

                for(int i = 1; i < subLength && curr != null && curr.next != null; i++){
                    curr = curr.next;
                }

                //找出下一波要切的起点
                ListNode next = null;
                if(curr != null){
                    next = curr.next;
                    curr.next = null;
                }

                //合并
                ListNode merged = merge(head1,head2);
                prev.next = merged;

                while(prev.next != null){
                    prev = prev.next;
                }

                curr = next;
            }
        }
        return dummy.next;
    }
    //合并两个有序链表
    private ListNode merge(ListNode l1, ListNode l2){
        ListNode dummy = new ListNode(0);
        ListNode curr = dummy;
        while(l1 != null && l2 != null){
            if(l1.val < l2.val){
                curr.next = l1;
                l1 = l1.next;
            }else{
                curr.next = l2;
                l2 = l2.next;
            }
            curr = curr.next;
        }
        curr.next = l1 != null ? l1 :l2;
        return dummy.next;
    }
}

1.遍历链表的长度

2.步长从1开始,每次*2

3.切出第一段和第二段用于排序

4.curr走到当前块的末尾

5.next找到下一步的起点

6.合并

7.将合并好的新块与数组连接起来

8.prev指针走到刚合并块的末尾

9.curr到下一波起点

相关推荐
江畔柳前堤7 小时前
大语言模型分布式训练:从并行策略到万卡工程的系统梳理
人工智能·分布式·深度学习·算法·目标检测·机器学习·语言模型
Doraemomo7 小时前
数据结构-环形链表
java·数据结构·链表
Forever Nore8 小时前
LeetCode 4 寻找两个正序数组的中位数 - 二分
算法·leetcode
罗西的思考9 小时前
【OpenClaw具身硬件】MiniClaw 阅读笔记---(1)基础
人工智能·算法·机器学习
蛋先生DX10 小时前
大模型参数存储格式揭秘:BF不是男朋友
深度学习·算法·llm
爱跳舞的烤冷面10 小时前
自学嵌入式第22天(数据结构——哈希)
数据结构·算法·哈希算法
猎嘤一号11 小时前
博弈论(Game Theory)的理论、算法与工程
人工智能·算法·安全·博弈论
月光船幽幽11 小时前
影子模式下保护 logits 不被修改
人工智能·python·算法
马拉AI11 小时前
腾讯开源 Agent 记忆系统,AI“换对话就忘”的问题有了新解法(附安装使用教程)
人工智能·算法·开源·科研
地平线开发者13 小时前
征程6工具链模型X86推理方式说明
算法