【leetcode】Merge k Sorted Lists(按大小顺序连接k个链表)

时间:2023-03-09 18:14:40
【leetcode】Merge k Sorted Lists(按大小顺序连接k个链表)

题目:Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

题意:把k个排序成一个有序链表。

用优先队列先把k个链表遍历一遍把值存起来,在建一个新链表吧数从优先队列里一个个放进去,注意空指针的判断。

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *mergeKLists(vector<ListNode *> &lists) {
int i,j,len=lists.size();
priority_queue<int,vector<int>,greater<int>> q;
int flag=1;
while(flag!=0)
{
flag=0;
for(i=0;i<len;++i)
{
if(lists[i])
{
flag=1;
q.push(lists[i]->val);
lists[i]=lists[i]->next;
}
}
}
if(q.empty())return NULL;
ListNode *root,*now;
root=new ListNode(q.top());
root->next=NULL;
now=root;
q.pop();
while(!q.empty())
{
now->next=new ListNode(q.top());
now=now->next;
q.pop();
now->next=NULL;
}
return root;
}
};