LeetCode 148. 排序链表

在 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
posted @ 2020-07-12 13:39  机器狗mo  阅读(75)  评论(0编辑  收藏  举报