Sort a linked list in O(n logn)
time using constant space
complexity.
Example 1:
Input: 4->2->1->3Output: 1->2->3->4
Example 2:
Input: -1->5->3->4->0Output: -1->0->3->4->5
根据题意的要求, 锁定使用归并排序
算法, 但是相对数组的归并排序, 有以下两个难点:
针对问题一, 可以使用快慢指针
来确认链表的中点, 快指针每次走两步, 慢指针每次走一步, 慢指针最后的位置就是链表的中点位置, 步骤图解如下:
针对奇数情形:
slowquickdummy -> 1 -> nullslow quickdummy -> 4 -> 2 -> 1 -> null偶数:slow quickdummy -> 1 -> 2 -> null
针对偶数情形:
slow quickdummy -> 1 -> 2 -> null
此外另外一个难点是如何进行 merge 操作。大体思路为
步骤图解如下:
lNode rNodedummy -> 1 -> 3 -> null 2 -> 4 -> nulllNode rNodedummy -> 1 -> 2 -> 3 -> null 4 -> null
var sortList = function(head) {const dummy = new ListNode(0)dummy.next = headlet head0 = dummy.nextlet slow = dummy, quick = dummywhile (quick.next) {quick = quick.nextslow = slow.nextquick.next && (quick = quick.next)}// if the slow list is equal to the quick list, it means the current list only has one node.if (slow === quick) return dummy.nextlet rightList = slow.nextslow.next = nulllet leftList = dummyreturn merge(sortList(leftList.next), sortList(rightList))}var merge = function(leftList, rightList) {const dummy = new ListNode(0)dummy.next = leftListlet lNode = dummylet rNode = rightListwhile (lNode && rNode) {while (lNode.next && lNode.next.val < rNode.val) {lNode = lNode.next}let rNext = rNode.nextrNode.next = lNode.nextlNode.next = rNoderNode = rNext}return dummy.next}
147、143、234