每日一题:LeetCode之排序列表

在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4
示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

思路:归并排序,递归使用快慢指针寻找列表中点,分割列表至每个列表只剩一个节点,再一一将列表合并

public ListNode sortList(ListNode head) {
        if(head==null)
            return null;
        return sort(head);

    }
    public ListNode sort(ListNode node){
        if(node.next==null)
            return node;
        ListNode slow= node;
        ListNode fast= node;
        while(fast.next!=null&&fast.next.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        fast=slow.next;
        slow.next=null;
        
        slow=sort(node);
        fast=sort(fast);

        return merge(slow,fast);

    }

    public ListNode merge(ListNode slow,ListNode fast){

        ListNode head=new ListNode(0);
        
        ListNode res=head;

        while(slow!=null&&fast!=null){
            if(slow.val<fast.val){
                res.next=slow;
                res=res.next;
                slow=slow.next;
            }else{
                res.next=fast;
                res=res.next;
                fast=fast.next;
            }
        }
        if(fast!=null)
            res.next=fast;
        else if(slow!=null)
            res.next=slow;
            
        return head.next;
    }
发布了28 篇原创文章 · 获赞 0 · 访问量 367

猜你喜欢

转载自blog.csdn.net/qq_40053995/article/details/105016546