MergeKSortedList

本文介绍了一种高效的方法来合并多个已排序的链表。通过使用优先队列(最小堆),该算法能够以O(n log k)的时间复杂度合并K个链表,其中n是所有链表中节点的总数,k是链表的数量。文章提供了完整的C++实现代码。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

将K个已排序的链表合并为一个有序的链表

输入:K个有序List

输出:一个有序List

代码:

/*
	Ethan
	mergeKSortedLists
	2016.3.1
*/
#include <iostream>
#include <vector>
#include <queue>
using namespace std;
struct ListNode{
	int val;
	ListNode *next;
	ListNode(int x) : val(x),next(NULL){}
};
class Solution {
	struct cmp{
		bool operator() (ListNode *x, ListNode *y){
			return x->val > y->val;
		}
	};
public:
	ListNode *mergeKLists(vector<ListNode*> &lists){
		ListNode *ret = NULL;
		ListNode **pCur = &ret;
		ListNode *tmp = NULL;
		if(lists.size()==0){
			return ret;
		}
		priority_queue<ListNode*,vector<ListNode*>,cmp> que;
		for(int i=0;i<lists.size();i++){
			if(lists[i]!=NULL){
				que.push(lists[i]);
			}
		}
		while(!que.empty()){
			tmp = que.top();
			que.pop();
			*pCur = tmp;
			pCur = &((*pCur)->next);
			if(tmp->next!=NULL){
				que.push(tmp->next);
			}
		}
		return ret;
	}
	void printList(ListNode *&a){
		while(a!=NULL){
			cout<<a->val<<"\t";
			a = a->next;
		}
		cout<<endl;
	}
};

int main(int argc, char *argv[]) {
	vector<ListNode*> lists;
	for(int j=1;j<6;j++){
		ListNode *list =new ListNode(0);
		list->next = NULL;
		ListNode *tmp;
		tmp = list;
		for(int i=1;i<6;i++){
			ListNode *p = new ListNode(i*j);
			tmp->next = p;
			tmp = p;
		}
		tmp->next = NULL;
		lists.push_back(list);
	}
	Solution a;
	ListNode *l = a.mergeKLists(lists);
	a.printList(l);
	return 0;
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值