Merge k Sorted Lists

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

class Solution {
public:
    struct Node{
        ListNode *p;
        Node(ListNode* pointer):p(pointer){    
        }
        //make heap的时候,k和2k 2k+1的孩子比较,这样就会采用< operator,如果为true,就进行swap
        //由此可见,需要this > rs.p->val
        bool operator < (const Node & rs) const{
            return p->val > rs.p->val;
        }
    };
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        if (lists.size() == 0) return NULL;
        if (lists.size() == 1) return lists[0];
        
        ListNode head(0),*h = &head;
        priority_queue<Node> pq;
        
        for(int i = 0; i < lists.size(); i++){
            if (lists[i]){
                pq.push(Node(lists[i]));
            }
        }
        while(!pq.empty()){
            Node node = pq.top();
            pq.pop();
            h = h->next = new ListNode(node.p->val);
            if (node.p->next){
                pq.push(Node(node.p->next));
            }
        }
        return head.next;
    }
};

 

posted @ 2013-07-14 18:07  一只会思考的猪  阅读(182)  评论(0编辑  收藏  举报