leetcode 23 合并K个升序链表
一、题目描述

二、解题思路
解法一:两两合并
整体思路
遍历lists向量,对每一个链表一一进行升序合并;
解法二:借助优先队列
借助优先队列(小根堆)来将判断结点的大小,每次弹出最小的结点,再进行尾插合并。
三、代码实现
解法一:两两合并
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {
public:ListNode* mergeKLists(vector<ListNode*>& lists) {//统计链表的个数int n=lists.size();//特殊情况处理if(n==0) return nullptr;if(n==1) return lists[0];//引入虚拟头节点ListNode* NewHead=new ListNode(0);for(auto l:lists)NewHead->next=my_merge(NewHead->next,l);//避免内存泄漏ListNode* ret=NewHead->next;delete NewHead;return ret;}ListNode* my_merge(ListNode* l1,ListNode* l2){//边界处理if(l1==nullptr) return l2;if(l2==nullptr) return l1;//虚拟头节点ListNode dmp(0);ListNode* NewHead=&dmp;ListNode* tail=NewHead;ListNode* cur1=l1;ListNode* cur2=l2;while(cur1&&cur2){if(cur1->val<=cur2->val){tail->next=cur1;cur1=cur1->next;}else{tail->next=cur2;cur2=cur2->next;}tail=tail->next;}//加上剩余的部分if(cur1) tail->next=cur1;if(cur2) tail->next=cur2;return NewHead->next;}
};解法二:借助优先队列
/*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode() : val(0), next(nullptr) {}* ListNode(int x) : val(x), next(nullptr) {}* ListNode(int x, ListNode *next) : val(x), next(next) {}* };*/
class Solution {struct cmp{bool operator()(const ListNode* l1,const ListNode* l2){return l1->val>l2->val;}};
public:ListNode* mergeKLists(vector<ListNode*>& lists) {//创建一个小根堆priority_queue<ListNode*,vector<ListNode*>,cmp> heap;//让所有头结点进入小根堆for(auto l:lists){if(l) heap.push(l);}//合并K个有序链表ListNode* ret=new ListNode(0);ListNode* prev=ret;while(!heap.empty()){ListNode* t=heap.top();heap.pop();prev->next=t;prev=t;if(t->next) heap.push(t->next);}prev=ret->next;delete ret;return prev;}
};