首页 > 代码库 > LeetCode 23 Merge k Sorted Lists

LeetCode 23 Merge k Sorted Lists

Description

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

多路排序的一个例子,用优先权队列保存指针,每次选出有最小的权值的指针,将其指向的节点加入结果链表。

努力改良自己代码风格,让自己的代码变得好看。技术分享

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    struct cmp
    {
        bool operator()(ListNode *a, ListNode *b)
        {
            return a->val > b->val;
        }
    };
    priority_queue<ListNode*, vector<ListNode* >, cmp > pq;

    ListNode* mergeKLists(vector<ListNode*>& lists) {
        for(int i = 0; i < lists.size(); i++)
        {
            if(lists[i] != NULL)
            {
                pq.push(lists[i]);
            }
        }
        ListNode *head = NULL;
        ListNode *p = NULL;
        while(!pq.empty())
        {
            ListNode *tmp = pq.top(); 
            pq.pop();
            
            if(head == NULL)
            {
                head = new ListNode(tmp->val);
                p = head;
            }
            else
            {
                ListNode *t = new ListNode(tmp->val);
                p->next = t;
                p = t;
            }
            tmp = tmp->next;
            if(tmp != NULL)
                pq.push(tmp);
        }

        return head;
    }
};

LeetCode 23 Merge k Sorted Lists