码迷,mamicode.com
首页 > 编程语言 > 详细

LeetCode 148. 排序链表

时间:2020-07-12 14:49:04      阅读:55      评论:0      收藏:0      [点我收藏+]

标签:node   not   list   val   init   复杂   排序   slow   linked   

在?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. 排序链表

标签:node   not   list   val   init   复杂   排序   slow   linked   

原文地址:https://www.cnblogs.com/sandy-t/p/13288142.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!