在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
思路:
递归排序,
1. 找中点,把链表一分为二
2. 递归处理左右半边
3. 合并排好序的部分
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
if not head or not head.next:
return head
pre, slow, fast = head, head, head
while fast and fast.next: #找链表中点
pre = slow
slow = slow.next
fast = fast.next.next
pre.next = None
left, right = self.sortList(head), self.sortList(slow)
return self.merge(left, right)
def merge(self, l1, l2):
if not l1:
return l2
if not l2:
return l1
if l1.val < l2.val:
head = ListNode(l1.val)
head.next = self.merge(l1.next, l2)
else:
head = ListNode(l2.val)
head.next = self.merge(l1, l2.next)
return head