给你链表的头结点 head ,请将其按 升序 排列并返回 排序后的链表 。
进阶:
你可以在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序吗?
示例 1:
输入:head = [4,2,1,3]
输出:[1,2,3,4]
示例 2:
输入:head = [-1,5,3,4,0]
输出:[-1,0,3,4,5]
示例 3:
输入:head = []
输出:[]
提示:
链表中节点的数目在范围 [0, 5 * 104] 内
-105 <= Node.val <= 105
来源:力扣(LeetCode)
链接:https://leetcode-cn.com/problems/sort-list
# Definition for singly-linked list.
# class ListNode(object):
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution(object):
def sortList(self, head):
"""
:type head: ListNode
:rtype: ListNode
"""
# step1:寻找中心点,划分左右区域
def findMid(head):
slow = head
fast = head
# 快慢指针的这个判断条件要注意
while fast.next and fast.next.next:
fast = fast.next.next
slow = slow.next
return slow
# step2:有序链表的双路归并
def merge(l,r):
dummy = ListNode(None)
p = dummy
while l and r:
if l.val <= r.val:
p.next = l
l = l.next
else:
p.next = r
r = r.next
p = p.next
p.next = l or r
return dummy.next
# step3:归并排序的主程序
if not head or not head.next:
return head
mid = findMid(head)
left = head
right = mid.next
mid.next = None #起到的作用把两个链表分开
l = self.sortList(left)
r = self.sortList(right)
return merge(l,r)