leetcode---SortList

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

对单链表进行排序,时间复杂度和空间复杂度决定了使用堆排序或者是快速排序。
采用的是堆排序,和数组不同的地方是需要找到中间的节点,然后递归进行分割到最下的单位,最后进行合并,合并的时候采用的是哑节点进行帮助,这样会方便的进行操作。

/**
 * Definition for singly-linked list.
 * public class ListNode {
 *     int val;
 *     ListNode next;
 *     ListNode(int x) { val = x; }
 * }
 */
public class Solution {
    public ListNode sortList(ListNode head) {
        if(head==null||head.next==null) return head;
        ListNode slow=head,fast=head.next.next;
        while(fast!=null&&fast.next!=null){
            slow=slow.next;
            fast=fast.next.next;
        }
        //找到中间的节点slow
        ListNode p1=sortList(slow.next);
        slow.next=null;
        ListNode p2=sortList(head);
        return merge(p1,p2);
    }


    public ListNode merge(ListNode i,ListNode j){
        ListNode p,dummy=new ListNode(0);
        p=dummy;
        while(i!=null&&j!=null){
            if(i.val<j.val){
                p.next=i;
                i=i.next;
            }
            else{
                p.next=j;
                j=j.next;
            }
            p=p.next;
        }
        p.next = (i==null?j:i);//合并剩余的
        return dummy.next;
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值