1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68

#include <queue>
#include <vector>
#include <list>
#include <iostream>

using namespace std;

struct ListNode 
{
    int val;
    ListNode *next;
    ListNode(int x = 0) : val(x), next(NULL) {}
};

class NodeCompare
{
public:
    bool operator()(ListNode *x, ListNode *y) {
        return (x->val > y->val);
    }
};

ListNode *MergeKLists(vector<ListNode *> &lists) 
{
    ListNode * head = NULL;
    ListNode ** previous = &head;
    ListNode *top = NULL;
    // the priority queue works like heap, we could get min value in O(1)
    // delete node and add new node take O(log n), n is size of lists.
    // It's better than compare each head node in lists, which takes O(n) 
    // to find current min
    priority_queue<ListNode *, vector<ListNode *>, NodeCompare> nexts;
    
    for (int i = 0; i < lists.size(); ++i)
        if(lists[i]) //push NULL pointer to queue
            nexts.push(lists[i]);
    
    while(!nexts.empty())
    {
        top = nexts.top();
        nexts.pop();
        (*previous) = top;
        previous = &(top->next);
        if (top->next)
        {
            nexts.push(top->next);
        }
    }
    
    return head;
}


int main(int argc, char** argv)
{
    ListNode lNodes[20];
    vector<ListNode *>  nodes;
    
    for (int i = 0; i < 20; ++i)
    {
        lNodes[i].val = i+1;
        nodes.push_back(lNodes+i);
    }
    
    
    MergeKLists(nodes);
    return 0;
}
View Program Text


Test Status