ACM下,利用小根堆实现K个链表合并,输入没有键盘输入,主要是为了提高一下面试的写入速度。就当练习了一下ACM。
#include<iostream>
#include<vector>
#include<queue>
using namespace std;
struct ListNode{
int val;
ListNode* next;
ListNode(int x) : val(x), next(nullptr){}//构造函数
ListNode(int x, ListNode *next) : val(x), next(next) {}
};
class mergeKList
{
public:
ListNode* merge(vector<ListNode*>& lists)
{
priority_queue<int, vector<int>, greater<int>> minHeap;//使用升序队列
//遍历链表放入优先队列中
for(ListNode* x : lists)
{
while(x)
{
minHeap.push(x->val);
x = x->next;
}
}
ListNode* dummyHead = new ListNode(-1);
ListNode* cur = dummyHead;
while(!minHeap.empty())
{
int top = minHeap.top();
minHeap.pop();
cur->next = new ListNode(top);
cur = cur->next;
}
return dummyHead->next;
}
};
//创建链表
ListNode* creat(vector<int>& num)
{
ListNode* head = new ListNode(num[0]);
ListNode* tmp = head;
for(int i = 1; i < num.size(); i++)
{
ListNode* node = new ListNode(num[i]);
tmp->next = node;
tmp = tmp->next;
}
return head;
}
int main(){
vector<int> vec1 {1,2,4};
vector<int> vec2 {3,5,7};
vector<int> vec3 {3,7,9};
vector<ListNode*> lists;
ListNode* head1 = creat(vec1);
ListNode* head2 = creat(vec2);
ListNode* head3 = creat(vec3);
lists.push_back(head1);
lists.push_back(head2);
lists.push_back(head3);
mergeKList Klist;
ListNode* head = Klist.merge(lists);
ListNode* temp = new ListNode(0);
temp = head;
while (temp) {
cout << temp->val << " -> ";
temp = temp->next;
}
cout << endl;
delete temp;
}