Leetcode 23. Merge k Sorted Lists

Merge k Sorted Lists :

給定一個由 k 個linked-lists 組成的數組,每個linked-lists 按升序排序。將所有linked-lists 合併為一個排序的linked-lists 並返回。

Python

創建一個List I ,保存每個linked-lists的值,之後再串聯到point 指針上,返回result.next即得到答案

class Solution(object):
    def mergeKLists(self, lists):
        l = []
        for i in lists:
            while i:
                l.append(i.val)
                i = i.next
        point = result = ListNode(0)
        for node in sorted(l):
            point.next = ListNode(node)
            point = point.next
        return result.next

C++

class Solution {
public:
  ListNode* mergeKLists(vector<ListNode*>& lists) {
    ListNode dummy(0);
    ListNode *cur = &dummy;
    
    auto comp = [](ListNode* a, ListNode* b) { return a->val > b->val; };
    priority_queue<ListNode*, vector<ListNode*>, decltype(comp)> q(comp);
    
    for (ListNode* list : lists) 
      if (list) q.push(list);
    
    while (!q.empty()) {
      cur->next = q.top(); q.pop();      
      cur = cur->next;
      if (cur->next) q.push(cur->next);
    }
    return dummy.next;
  }
};