LeetCode 148. 排序連結串列
阿新 • • 發佈:2020-07-12
在 O(n log n) 時間複雜度和常數級空間複雜度下,對連結串列進行排序。
示例 1:
輸入: 4->2->1->3
輸出: 1->2->3->4
示例 2:
輸入: -1->5->3->4->0
輸出: -1->0->3->4->5
# Definition for singly-linked list. # class ListNode: # def __init__(self, x): # self.val = x # self.next = None class Solution: def sortList(self, head: ListNode) -> ListNode: if head is None or head.next is None: return head slow = head fast = head.next while fast is not None and fast.next is not None: slow = slow.next fast = fast.next.next mid = slow.next slow.next = None pre_head = ListNode(None) cur = pre_head p1 = self.sortList(head) p2 = self.sortList(mid) while p1 is not None and p2 is not None: #print(p1.val,p2.val) if p1.val < p2.val: cur.next = p1 p1 = p1.next else: cur.next = p2 p2 = p2.next cur = cur.next if p1 is not None: cur.next = p1 if p2 is not None: cur.next = p2 return pre_head.next