题目:
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例1:
输入: 4->2->1->3
输出: 1->2->3->4
示例2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
算法实现:
合并排序 + 递归
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
slow = head
fast = head.next
while fast and fast.next:
fast = fast.next.next
slow = slow.next
mid = slow.next
slow.next = None
left = self.sortList(head)
right = self.sortList(mid)
result = temp = ListNode(0)
while left and right:
if left.val >= right.val:
temp.next = right
right = right.next
else:
temp.next = left
left = left.next
temp = temp.next
temp.next = left if left else right
return result.next