148. Sort List(js)

148. Sort List

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

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5
题意:链表排序,时间复杂度nlogn
代码如下:
/**
 * Definition for singly-linked list.
 * function ListNode(val) {
 *     this.val = val;
 *     this.next = null;
 * }
 */
/**
 * @param {ListNode} head
 * @return {ListNode}
 */
// 归并排序
var sortList = function(head) {
    if(!head || !head.next) return head;
    let pre=head,slow=head,fast=head;
    while(fast && fast.next){
        pre=slow;
        slow=slow.next;
        fast=fast.next.next;
    }
    pre.next=null;
    return merge(sortList(head),sortList(slow));
};
var merge=function(l1,l2){
    let node=new ListNode(-1);
    let cur=node;
    while(l1 && l2){
        if(l1.val<l2.val){
            cur.next=l1;
            l1=l1.next;
        }else{
            cur.next=l2;
            l2=l2.next;
        }
        cur=cur.next;
    }
    if(l1) cur.next=l1;
    if(l2) cur.next=l2;
    return node.next;
}

 

posted @ 2019-06-25 19:29  mingL  阅读(341)  评论(0编辑  收藏  举报