LeetCode 148. 排序链表

Posted 机器狗mo

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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




以上是关于LeetCode 148. 排序链表的主要内容,如果未能解决你的问题,请参考以下文章

LeetCode Algorithm 148. 排序链表

[Leetcode]148. 排序链表(归并排序)

LeetCode 148. 排序链表

精选力扣500题 第43题 LeetCode 148. 排序链表c++/java详细题解

LeetCode | 148. 排序链表

LeetCode Java刷题笔记—148. 排序链表