合并K个排序链表(链表类优队)

题目:https://leetcode-cn.com/problems/merge-k-sorted-lists/submissions/

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };
 */
class Solution {
public:
    struct cmp{//优队使用配套cmp
    	bool operator () (const ListNode *a,const ListNode *b) {
    		return a->val > b->val;
		}
	};
    ListNode* mergeKLists(vector<ListNode*>& lists) {
        /*
        *优队链表
        *将有序链表都丢进队列,每次取最小的出来即可
        *
        */
        priority_queue<ListNode*,vector<ListNode*>,cmp> q;//链表类优队
        int n = lists.size();
        for(int i = 0;i < n;i++) 
            if(lists[i] != NULL)
                q.push(lists[i]);
        ListNode *ans= new ListNode(-1);
        ListNode *p = ans;
        while(!q.empty()) {
            ListNode *cur = q.top();
            q.pop();
            p->next = new ListNode(cur->val);
            p = p->next;
            if(cur->next != NULL) q.push(cur->next);
        }
        return ans->next;
    }
    
};
发布了71 篇原创文章 · 获赞 1 · 访问量 2800

猜你喜欢

转载自blog.csdn.net/weixin_43918473/article/details/104313833