【python3】leetcode 148. Sort List (Medium)
阿新 • • 發佈:2019-01-09
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->4Example 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]