在 O(n log n) 時間複雜度和常數級空間複雜度下,對鏈表進行排序。spa
示例 1:code
輸入: 4->2->1->3
輸出: 1->2->3->4
示例 2:blog
輸入: -1->5->3->4->0
輸出: -1->0->3->4->5排序
插入排序,確定超時了,時間複雜度最壞是O(n^2)io
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
歸併ast
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