-
题目链接
-
解题思路:在链表上使用排序算法。注意,不能使用快排,因为快排的最差时间复杂度是
O(n^2)
,数组形式的快排,以随机数划分能够得到O(n*logn)
,但是链表的形式,不太好以随机数的方式划分。所以最好的排序方法是使用归并排序。- 先用快慢指针,将链表分成两部分,然后两部分分别归并排序,得到两个链表的头和尾。然后再
merge
即可
- 先用快慢指针,将链表分成两部分,然后两部分分别归并排序,得到两个链表的头和尾。然后再
-
代码
class Solution:def process(self, node: Optional[ListNode]) -> (Optional[ListNode], Optional[ListNode]):slow = nodeif slow.next == None:return slow, slowfast = slow.nextwhile fast and fast.next:slow = slow.nextfast = fast.nextif fast == None:breakfast = fast.next# 分别有序tmp = slow.nextslow.next = Nonehead1, tail1 = self.process(node)head2, tail2 = self.process(tmp)# 合并ans_head = Noneans_tail = tail1 if tail1.val >= tail2.val else tail2if head1.val <= head2.val:ans_head = head1head1 = head1.nextelse:ans_head = head2head2 = head2.nextcur = ans_headwhile head1 and head2:if head1.val <= head2.val:cur.next = head1head1 = head1.nextelse:cur.next = head2head2 = head2.nextcur = cur.nextif head1:cur.next = head1if head2:cur.next = head2return ans_head, ans_taildef sortList(self, head: Optional[ListNode]) -> Optional[ListNode]:if head == None:return Nonehead1, _ = self.process(head)return head1