1. 程式人生 > >leetcode#23 Merge k Sorted Lists

leetcode#23 Merge k Sorted Lists

lists nod pop top describe b- list node 最大

Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Example:

Input:
[
1->4->5,
1->3->4,
2->6]
Output: 1->1->2->3->4->4->5->6

//k個鏈表先丟進堆去,使用最小堆,我們取出最小那個,再放回去next結點,直到堆為空
//為此,我們需要為堆修改比較規則
//


struct cmp {//默認是最大堆,也就是使用了<,因此,我們修改比較規則
    bool operator () (ListNode *a, ListNode *b) {
        return a->val > b->val;
    }
};

class Solution {  
public:  
    ListNode *mergeKLists(vector<ListNode *> &lists) 
    {  
        priority_queue<ListNode*, vector<ListNode*>, cmp> q;
        for (int i = 0; i < lists.size(); ++i) 
            if (lists[i]) 
                q.push(lists[i]);

        ListNode *head = NULL, *pre = NULL, *tmp = NULL;
        while (!q.empty()) {
            tmp = q.top();
            q.pop();
            if (!pre) head = tmp;
            else pre->next = tmp;
            pre = tmp;
            if (tmp->next) q.push(tmp->next);
        }
        return head;
    }  
};

leetcode#23 Merge k Sorted Lists