LeetCode--148--排序链表(python)

在 O(n log n) 时间复杂度和常数级空间复杂度下,对链表进行排序。

示例 1:

输入: 4->2->1->3
输出: 1->2->3->4
示例 2:

输入: -1->5->3->4->0
输出: -1->0->3->4->5

插入排序,肯定超时了,时间复杂度最坏是O(n^2)

 1 class Solution:
 2     def sortList(self, head: ListNode) -> ListNode:
 3         if head==None or head.next==None:
 4             return head
 5         dummyY=ListNode(0)
 6         dummyY.next=head
 7         p = head
 8         r = p.next
 9         p.next=None
10         p=r
11         while p != None:
12             pre = dummyY
13             r = p.next
14             while pre.next!=None and pre.next.val <p.val:
15                 pre = pre.next
16             p.next = pre.next
17             pre.next = p
18             p = r            
19         return dummyY.next

 归并

 1 class Solution:
 2     def sortList(self, head: ListNode) -> ListNode:
 3         if not head or not head.next:return head
 4         slow,fast = head,head.next
 5         while fast and fast.next:
 6             fast,slow=fast.next.next,slow.next
 7         mid,slow.next=slow.next,None
 8         left,right=self.sortList(head),self.sortList(mid)
 9         
10         h=res = ListNode(0)
11         while left and right:
12             if left.val < right.val :h.next,left=left,left.next
13             else:h.next,right=right,right.next
14             h=h.next
15         h.next=left if left else right
16         return res.next
原文地址:https://www.cnblogs.com/NPC-assange/p/11650237.html