码迷,mamicode.com
首页 > 其他好文 > 详细

Merge k Sorted Lists

时间:2015-01-31 14:40:42      阅读:190      评论:0      收藏: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;
}


Merge k Sorted Lists

标签:

原文地址:http://blog.csdn.net/li_chihang/article/details/43340501

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!