302.LeetCode | 23. 合并K个升序链表
每天一个开发小知识
01
给你一个链表数组,每个链表都已经按升序排列
请你将所有链表合并到一个升序链表中,返回合并后的链表
/**
* 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) {
vector<ListNode*> pos;
for (auto iter : lists)
{
pos.push_back(iter);
}
ListNode * dummy = new ListNode();
ListNode * p = dummy;
while (NULL != p)
{
int index = -1;
for (int i = 0; i < pos.size(); ++i)
{
if (NULL != pos[i])
{
if (-1 == index || pos[i]->val < pos[index]->val)
{
index = i;
}
}
}
if (-1 != index)
{
p->next = pos[index];
pos[index] = pos[index]->next;
}
p = p->next;
}
return dummy->next;
}
};