*Sort List - Leetcode

本文介绍了一种在O(n log n)时间内使用常数空间复杂度对单向链表进行排序的方法。通过快慢指针找到中点,并采用递归方式实现归并排序。

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

/**
 * Definition for singly-linked list.
 * class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) {
 *         val = x;
 *         next = null;
 *     }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        ListNode fast=head, slow=head;
        if(fast == null || fast.next == null)
           return head;
           
        while(fast.next != null && fast.next.next != null){
            fast=fast.next.next;
            slow=slow.next;
        }
        
        ListNode head2 = slow.next;
        slow.next=null;
        
        ListNode l1 = sortList(head);
        ListNode l2 = sortList(head2);
        return mergeList(l1,l2);
    }
    private ListNode mergeList(ListNode l1, ListNode l2){
        ListNode nd = new ListNode(-1);
        ListNode p = nd;
        while(l1!=null && l2!=null){
           if( v1 <= v2){
               p.next = l1;
               l1 = l1.next;
           }else{
               p.next = l2;
               l2 = l2.next;
           }
           p = p.next;
        }
        p.next = l1!=null? l1: l2;
        return nd.next;
    }
}


分析: nlogn的要求,就要确定一般的排序肯定不行。单向链表用归并,双向链表用快排。 tricky的地方:快慢指针找中间点;mergelist返回总是排序完成之后的head.

Sort a linked list in O(n log n) time using constant space complexity.


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值