/*
* function ListNode(x){
* this.val = x;
* this.next = null;
* }
*/
/**
*
* @param head ListNode类 the head node
* @return ListNode类
*/
function sortInList( head ) {
if(head==null||head.next==null){
return head
}
let slow = head,fast = head.next
while(fast!=null&&fast.next!=null){
slow = slow.next
fast = fast.next.next
}
let newList = slow.next
slow.next = null
return merge(sortInList(head),sortInList(newList))
}
function merge(left,right){
let newHead = new ListNode(-1)
let current = newHead
while(left && right){
if(left.val<right.val){
current.next = left
left = left.next
}else{
current.next = right
right = right.next
}
current = current.next
}
while(left){
current.next = left
left = left.next
current = current.next
}
while(right){
current.next = right
right = right.next
current = current.next
}
return newHead.next
}
module.exports = {
sortInList : sortInList
};
“相关推荐”对你有帮助么?
-
非常没帮助
-
没帮助
-
一般
-
有帮助
-
非常有帮助
提交