148. Sort List

2018-06-20  本文已影响0人  April63

嗯 stack 的办法很low对不对。

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        stack = []
        while head:
            stack.append(head.val)
            head = head.next
        dummy = ListNode(0)
        p = dummy
        stack.sort()
        while stack:
            p.next = ListNode(stack.pop(0))
            p = p.next
        return dummy.next

阿里当时面试官提示的一种基于二分法的一种办法,类似于快排。。
二分 归并
代码如下:

# Definition for singly-linked list.
# class ListNode(object):
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution(object):
    def sortList(self, head):
        """
        :type head: ListNode
        :rtype: ListNode
        """
        if not head or not head.next:
            return head
        pre = ListNode(0)
        slow = head
        fast = head
        while fast and fast.next:
            pre = slow
            slow = slow.next
            fast = fast.next.next
        pre.next = None
        l1 = self.sortList(head)
        l2 = self.sortList(slow)
        return self.merge(l1, l2)
    def merge(self, l1, l2):
        if not l1:
            return l2
        if not l2:
            return l1
        l = ListNode(0)
        p = l
        while l1 and l2:
            if l1.val < l2.val:
                p.next = l1
                l1 = l1.next
                p = p.next
            else:
                p.next = l2
                l2 = l2.next
                p = p.next
        if l1:
            p.next = l1
        if l2:
            p.next = l2
        return l.next
     
上一篇下一篇

猜你喜欢

热点阅读