分类:链表
难度:medium
方法:归并排序
在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。
示例 1:
输入: 4->2->1->3
输出: 1->2->3->4
示例 2:
输入: -1->5->3->4->0
输出: -1->0->3->4->5
题解
来源于https://leetcode-cn.com/problems/sort-list/solution/sort-list-gui-bing-pai-xu-lian-biao-by-jyd/
主要分为两步
如何在链表中找到中点并且切分(快慢指针)
如何在O(1)的空间复杂度合并两个链表
递归即可
代码
# Definition for singly-linked list.
# 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,fast = head,head.next
while fast and fast.next:
fast = fast.next.next
slow = slow.next
mid = slow.next
slow.next =None
left,right = self.sortList(head),self.sortList(mid)
pos = res = ListNode(-1)
while left and right:
if left.val<right.val:
pos.next = left
left = left.next
else:
pos.next = right
right = right.next
pos = pos.next
pos.next = left if left else right
return res.next