【python3】leetcode 148. Sort List (Medium)

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/maotianyi941005/article/details/86107055

 148. Sort List (Medium)

Sort a linked list in O(n log n) time using constant space complexity.

Example 1:

Input: 4->2->1->3
Output: 1->2->3->4

Example 2:

Input: -1->5->3->4->0
Output: -1->0->3->4->5

1 先不考虑题目要求的O(nlogn)和常数空间 

# 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:return []
        A = []
        a = head
        while(a):
            A.append(a)
            a = a.next
        A = sorted(A,key = lambda x :x.val)
        for i in range(len(A)-1):
            A[i].next = A[i+1]
        A[-1].next = None
        return A[0]

猜你喜欢

转载自blog.csdn.net/maotianyi941005/article/details/86107055
今日推荐