diff --git a/README.md b/README.md index b9e3a66..993358f 100644 --- a/README.md +++ b/README.md @@ -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 diff --git a/src/list/sort-list.js b/src/list/sort-list.js new file mode 100644 index 0000000..124dd46 --- /dev/null +++ b/src/list/sort-list.js @@ -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) +} diff --git a/test/list/sort-list.test.js b/test/list/sort-list.test.js new file mode 100644 index 0000000..4eb18d2 --- /dev/null +++ b/test/list/sort-list.test.js @@ -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])) +})