Leetcode 148. Sort List python
Leetcode 148. Sort List 题目 解法1:利用最小堆 解法2:利用归并排序的思想 题目 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:利用最小堆 循环一次整个链表,将node的值存入一个最小堆中,再循环这个最小堆,将元素一次pop出来,构建新链表 class Solution ( object ) : def sortList ( self , head ) : """ :type head: ListNode :rtype: ListNode """ if not head : return None l = [ ] while head : heapq . heappush ( l , head . val ) head = head . next first_val = heapq . heappop ( l ) first = ListNode ( first_val ) tmp = first while l : curr_val = heapq