Merge k Sorted Lists

使用优先级队列

struct cmp{
    bool operator() ( ListNode* a, ListNode* b ){
        return a->val>b->val;
    }
};

class Solution {
public:
    ListNode *mergeKLists(vector<ListNode *> &lists) {
        // Note: The Solution object is instaentiated only once and is reused by each test case.
        int k = lists.size();
        priority_queue<ListNode*,vector<ListNode*>,cmp> q;
        for(int i=0;i<k;i++)
        {
            if(lists[i])  //attention, judege if it's NULL
                q.push(lists[i]);
        }
            
        ListNode* newHead = NULL;
        ListNode* tail;
        while(!q.empty())
        {
            ListNode* n = q.top();
            q.pop();
            if(!newHead)
                tail = newHead = n;
            else
            {
                tail->next = n;
                tail = n;
            }
            
            if(n->next)
                q.push(n->next);
        }
        
        return newHead;
    }
};

  

posted @ 2013-10-09 16:47  summer_zhou  阅读(136)  评论(0编辑  收藏  举报