题目:
给你链表的头结点 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
来源:https://leetcode-cn.com/problems/sort-list
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, val=0, next=None):
# self.val = val
# self.next = next
class Solution:
def sortList(self, head: ListNode) -> ListNode:
if head is None or head.next is None:
return head
p1,p2=head.next,head
while p1 and p1.next:
p1=p1.next.next
p2=p2.next
mid=p2.next
p2.next=None
return(self.merge(self.sortList(head),self.sortList(mid)))
def merge(self,head: ListNode,tail: ListNode):
tmp=result=ListNode(0)
while head and tail:
if head.val <tail.val:
tmp.next=head
head=head.next
else:
tmp.next=tail
tail=tail.next
tmp=tmp.next
if head:
tmp.next=head
else:
tmp.next=tail
return result.next