合并K个有序链表

K个有序链表,用一个函数合并它们,并返回最终合并的结果:

代码如下:

    ListNode *mergeKLists(vector<ListNode *> &lists) {
        // Start typing your C/C++ solution below
        // DO NOT write int main() function
        priority_queue<Node> q;
        ListNode L(1);
        ListNode* c = &L;
        L.next = NULL;
        for (int i = 0; i < lists.size(); ++i)
        {
            if (lists[i] != NULL)
            {
                Node n;
                n.index = i;
                n.value = lists[i]->val;
                // lists[i] = lists[i]->next;
                q.push(n);
            }
        }
        while (!q.empty())
        {
            Node x = q.top();
            q.pop();
            c->next = lists[x.index];
            c = c->next;
            lists[x.index] = lists[x.index]->next;
            if (lists[x.index] != NULL)
            {
                x.value = lists[x.index]->val;
                q.push(x);
            }
        }
        c->next = NULL;
        return L.next;
    }

 

posted @ 2013-01-03 19:24  David Luo  阅读(1204)  评论(0编辑  收藏  举报