148. Sort List(js)

Posted xingguozhiming

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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;

 

以上是关于148. Sort List(js)的主要内容,如果未能解决你的问题,请参考以下文章

[Lintcode]98. Sort List/[Leetcode]148. Sort List

148. Sort List

[LeetCode] 148. Sort List

148. Sort List

#Leetcode# 148. Sort List

148. Sort List