leetcode148.排序链表
leetcode148.排序链表
题目
给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
用例
输入:head = [4,2,1,3]
输出:[1,2,3,4]
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
求解
/**
* Definition for singly-linked list.
* function ListNode(val, next) {
* this.val = (val===undefined ? 0 : val)
* this.next = (next===undefined ? null : next)
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
var sortList = function(head) {
if(head==null||head.next==null){
return head
}
//二分分两段(递归分)
let fast = head
let slow = head
while(fast.next!=null){
fast=fast.next
if(fast.next==null){
break
}
fast=fast.next
slow=slow.next
}
let last = slow.next
slow.next = null
//一切正常
let left = sortList(head)
let right = sortList(last)
//出问题了24变成4了
//排序
let p1 = left
let p2 = right
let new_head=null
if(p1.val<p2.val){
new_head = p1
p1=p1.next
}else{
new_head=p2
p2=p2.next
}
let p=new_head
p.next = null
while(p1!=null&&p2!=null){
if(p1.val<p2.val){
p.next = p1;
p1=p1.next;
}else{
p.next = p2;
p2=p2.next;
}
p=p.next
p.next=null
}
if(p1!=null){
p.next = p1
}
if(p2!=null){
p.next = p2
}
return new_head
};

浙公网安备 33010602011771号