/**
* 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) {
// Start typing your C/C++ solution below
// DO NOT write int main() function
if (lists.size() == 0)
return NULL;
ListNode *head = NULL;
ListNode *pCur = NULL;
std::vector<ListNode *>::iterator itr;
while (true)
{
itr = lists.begin();
std::vector<ListNode *>::iterator smallestItr = itr;
int smallestNum = 10000;
for (; itr != lists.end(); ++itr)
{
if ((*itr))
{
if ((*itr)->val < smallestNum)
{
smallestItr = itr;
smallestNum = (*itr)->val;
}
}
}
if ((*smallestItr))
{
if (head == NULL)
{
head = pCur = (*smallestItr);
}
else
{
pCur->next = (*smallestItr);
pCur = pCur->next;
}
(*smallestItr) = (*smallestItr)->next;
}
else
{
if (pCur)
pCur->next = NULL;
break;
}
}
return head;
}
};
leetcode: Merge k Sorted Lists
最新推荐文章于 2022-05-22 19:43:19 发布