Merge k Sorted Lists

16 篇文章 0 订阅

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

解题思路:一般而言,合并两个有序链表较为简单,只需要两两逐个比较即可.而本题要求合并K个有序链表,事实上只需要对每个链表的头结点建堆.每次输出最小值.并插入其所在链表的下个结点并维护堆.可以利用STL中的优先队列来完成.

#include<iostream>
#include<vector>
#include<queue>
#include<functional>
using namespace std;

//Definition for singly - linked list.
struct ListNode {
	int val;
	ListNode *next;
	ListNode(int x) : val(x), next(NULL) {}
};

struct ListCompare :public binary_function<ListNode*, ListNode*, bool>{
	bool operator()(const ListNode*& x, const ListNode*& y)const{ return x->val < y->val; }
};
ListNode *mergeKLists(vector<ListNode *> &lists) {
	priority_queue<ListNode*, vector<ListNode*>, ListCompare> Q_queue;
	for_each(lists.begin(), lists.end(), [&Q_queue](ListNode* head){if(head!=NULL)Q_queue.push(head);});     //建堆
	ListNode* ResultNode = new ListNode(0);
	ListNode* TmpNode = ResultNode;
	while (!Q_queue.empty()){
		ListNode* TopListNode = Q_queue.top();
		Q_queue.pop();
		TmpNode->next = TopListNode;
		TmpNode = TmpNode->next;
		if (TopListNode->next != NULL)
			Q_queue.push(TopListNode->next);
	}
	return ResultNode->next;
}


  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值