algorithm
algorithm copied to clipboard
148. 排序链表

/**
* 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 == null || head.next == null) return head;
let fast = head.next, slow = head;
while (fast != null && fast.next != null) {
slow = slow.next;
fast = fast.next.next
}
let temp = slow.next;
slow.next = null;
let left = sortList(head)
let right = sortList(temp)
let h = new ListNode(0)
let res = h
while (left != null && right != null) {
if (left.val < right.val) {
h.next = left
left = left.next
} else {
h.next = right
right = right.next
}
h = h.next
}
h.next = left != null ? left : right
return res.next
};