合并K个连续链表

// algorithm.cpp : 定义控制台应用程序的入口点。

#include "stdafx.h"
#include<iostream>
#include<vector>
#include<queue>

using namespace std;

struct ListNode{
	int val;
	ListNode* next;
	ListNode(int x) :val(x){}
};

ListNode* makeList(vector<int>& vec)
{
	ListNode* head = new ListNode(vec[0]);
	ListNode*pt = head;
	for (int i = 1; i < vec.size(); ++i){
		pt->next = new ListNode(vec[i]);
		pt = pt->next;
	}
	pt->next = nullptr;
	return head;
}

void printList(ListNode* head){
	ListNode* pt = head;
	while (pt){
		cout << pt->val << "->";
		pt = pt->next;
	}
	
}

class Cmp{
public:
	bool operator()(const ListNode* p1, const ListNode* p2){
		if (p1 && p2)
		{
			return p1->val > p2->val;//小顶堆
		}
	}
};
auto cmp = [](const ListNode* &a, const ListNode* &b) { return a->val < b->val; };

ListNode* mergeLists(vector<ListNode*>& Lists){
	ListNode* resNode = new ListNode(0);
	ListNode* pt = resNode;

	priority_queue<ListNode*, vector<ListNode* >, Cmp> que;
	for (auto x : Lists){
		if (x == nullptr){
			continue;
		}
		que.push(x);
	}

	while (!que.empty()){
		ListNode* temp = que.top();
		pt->next = temp;
		pt = pt->next;
		que.pop();
		if (temp->next!=nullptr){
			que.push(temp->next);
		}
	}
	return resNode->next;

}

int _tmain(int argc, _TCHAR* argv[])
{
	vector<int> a1 = { 1, 3 };
	vector<int> a2 = { 4, 5 };
	vector<int> a3 = { 2, 9 };
	ListNode* p1 = makeList(a1);
	ListNode* p2 = makeList(a2);
	ListNode* p3 = makeList(a3);
	vector<ListNode*>pp = { p1, p2, p3 };
	printList(mergeLists(pp));
	system("pause");
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值