排序链表

该博客介绍了如何使用分治法对链表进行排序,通过快慢指针找到链表中间节点,然后递归地对左右两部分进行排序,并通过归并操作将已排序的链表合并,最终达到O(nlogn)的时间复杂度和常数级空间复杂度的链表排序解决方案。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

题目来源

排序链表

题目描述

给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
在这里插入图片描述

思路分析

在这里插入图片描述

题目解答

class Solution {
    public ListNode sortList(ListNode head) {
        return  sortList(head,null);
    }
    public ListNode sortList(ListNode head,ListNode tail){
        if(head==null){
            return null;
        }
        if(head.next==tail){
            head.next=null;
            return head;
        }
        ListNode fast=head;
        ListNode slow=head;
        while(fast!=tail){
            fast=fast.next;
            slow=slow.next;
            if(fast!=tail){
                fast=fast.next;
            }
        }
        ListNode mid=slow;
        ListNode l1=sortList(head,mid);
        ListNode l2=sortList(mid,tail);
        ListNode sorted=merge(l1,l2);
        return sorted;
    }
    public ListNode merge(ListNode l1,ListNode l2){
        if(l1==null){
            return l2;
        }
         if(l2==null){
            return l1;
        }
        ListNode cur1=l1;
        ListNode cur2=l2;
        ListNode newHead=new ListNode(-1);
        ListNode newTail=newHead;
        while(cur1!=null&&cur2!=null){
            if(cur1.val<cur2.val){
                newTail.next=cur1;
                newTail=newTail.next;
                cur1=cur1.next;
            }else{
                newTail.next=cur2;
                newTail=newTail.next;
                cur2=cur2.next;
            }
        }
        if(cur1==null){
            newTail.next=cur2;
        }
        if(cur2==null){
            newTail.next=cur1;
        }
        return newHead.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值