add: 链表排序

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

View File

@ -276,3 +276,8 @@ LeetCode 与 LintCode 解题记录。此为个人练习仓库,代码中对重
- LeetCode 21. 合并两个有序链表 https://leetcode-cn.com/problems/merge-two-sorted-lists/
- LintCode 165. 合并两个排序链表 https://www.lintcode.com/problem/merge-two-sorted-lists/description
- [链表排序](src/list/sort-list.js)
- LeetCode 148. 排序链表 https://leetcode-cn.com/problems/sort-list/
- LintCode 98. 链表排序 https://www.lintcode.com/problem/sort-list/description

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)
}

View File

@ -0,0 +1,31 @@
import { sortList } from '../../src/list/sort-list'
function ListNode (val) {
this.val = val
this.next = null
}
const arrToList = (arr) => {
const head = new ListNode(arr[0])
let current = head
for (let n = 1, len = arr.length; n < len; n++) {
current.next = new ListNode(arr[n])
current = current.next
}
return head
}
test('链表排序', () => {
const source = [4, 2, 1, 3]
expect(sortList(arrToList(source))).toEqual(arrToList(source.sort((a, b) => a - b)))
const source2 = [-1, 5, 3, 4, 0]
expect(sortList(arrToList(source2))).toEqual(arrToList(source2.sort((a, b) => a - b)))
const source3 = [1, 3, 2, null]
expect(sortList(arrToList(source3))).toEqual(arrToList([1, 2, 3]))
const source4 = [1, 7, 2, 6, null]
expect(sortList(arrToList(source4))).toEqual(arrToList([1, 2, 6, 7]))
})