LeetCode 23 Merge k Sorted Lists

Posted 可达龙

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了LeetCode 23 Merge k Sorted Lists相关的知识,希望对你有一定的参考价值。

Description

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

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

努力改良自己代码风格,让自己的代码变得好看。Open-mouthed smile

/**
 * 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的主要内容,如果未能解决你的问题,请参考以下文章

[LeetCode] 23. Merge k Sorted Lists

[LeetCode] 23. Merge k Sorted Lists 合并k个有序链表

[LeetCode]23. Merge k Sorted Lists

leetcode23. Merge k Sorted Lists

leetCode 23. Merge k Sorted Lists

leetcode 23. Merge k Sorted Lists