一、思路:
第一种:求出每一个链表的最小值,然后把这个节点放到合并的结果链表里面,这个链表指向next
第二种:优先级队列,头结点放到优先级队列里面,将top的那一个放到合并的链表里面,再讲top指向next,push到队列里面
二、代码
第一种思路:
class Solution {
public:
ListNode *insert(ListNode *nowNode, int val) {
if (nowNode == NULL)
return new ListNode(val);
else {
nowNode->next = new ListNode(val);
return nowNode->next;
}
}
ListNode* mergeKLists(vector<ListNode*>& lists) {
ListNode *res = NULL, *nowNode = res;
while (true) {
bool isAllNull = true;
int minVal = INT_MAX, pos = -1;
for (int i = 0; i < lists.size(); i++)
{
if (lists[i] != NULL) {
isAllNull = false;
if (lists[i]->val < minVal) {
pos = i;
minVal = lists[i]->val;
}
}
}
if (isAllNull)
return res;
lists[pos] = lists[pos]->next;
if