add: 链表排序

This commit is contained in:
2020-05-02 13:34:49 +08:00
parent b665d6595e
commit 4cb154f7c7
3 changed files with 67 additions and 0 deletions

31
src/list/sort-list.js Normal file
View File

@ -0,0 +1,31 @@
import { mergeTwoLists } from './merge-two-sorted-lists'
/**
* Definition for singly-linked list.
* function ListNode(val) {
* this.val = val;
* this.next = null;
* }
*/
/**
* @param {ListNode} head
* @return {ListNode}
*/
export const sortList = function (head) {
if (head === null || head.next === null) return head
let slow = head
let fast = head
while (fast !== null) {
fast = fast.next
fast = fast !== null ? fast.next : null
if (fast !== null) {
slow = slow.next
}
}
const half = slow.next
slow.next = null
const left = sortList(head)
const right = sortList(half)
return mergeTwoLists(left, right)
}