add: 链表排序
This commit is contained in:
1 parent
b665d6595e
commit
4cb154f7c7
3 files changed
+67
No files matched your search
@@ -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)
|
||||
}
|
||||
Reference in new issue
Block a user