LSGO——LeetCode實戰(數組系列):148題 排序鏈表(Sort List)

原題:

在 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(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def sortList(self, head):
        h, length, intv = head, 0, 1 
        while h: 
            h, length = h.next, length + 1
        res = ListNode(0)  # 創建輔助鏈表,存儲排序的鏈節點
        res.next = head
        # 不斷的合併鏈節點
        while intv < length:
            pre, h = res, res.next
            while h:
                # 得到兩個合併的節點h1,h2
                h1, i = h, intv
                while i and h: 
                    h, i = h.next, i - 1
                if i: 
                    break # 如果i不爲0,則說明h1鏈的節點數不足intv個,那麼h2 is None
                h2, i = h, intv
                while i and h: 
                    h, i = h.next, i - 1
                c1, c2 = intv, intv - i # h2的長度可能沒有intv,所以由intv-i得
                # 合併h1和h2
                while c1 and c2:
                    if h1.val < h2.val: 
                        pre.next, h1, c1 = h1, h1.next, c1 - 1
                    else: 
                        pre.next, h2, c2 = h2, h2.next, c2 - 1
                    pre = pre.next
                # 之後c1或c2必有一個爲0.
                pre.next = h1 if c1 else h2
                while c1 > 0 or c2 > 0: 
                    pre, c1, c2 = pre.next, c1 - 1, c2 - 1
                pre.next = h #連接下一部分的intv
            intv *= 2
        return res.next

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章