https://leetcode.com/problems/merge-k-sorted-lists/description/
/**
* 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 begin = 0;
int end = lists.size() - 1;
if(end < 0) return NULL;
while(end > 0)
{
begin = 0;
while(begin < end)
{
lists[begin] = merge2Lists(lists[begin], lists[end]);
begin ++;
end --;
}
}
return lists[0];
}
ListNode* merge2Lists(ListNode* list1, ListNode* list2)
{
//ListNode dummy(0);
//ListNode* cur = &dummy;
ListNode* dummy = new ListNode(0);
ListNode* cur = dummy;
ListNode* dummy = new ListNode(0)
while(list1 && list2)
{
if(list1->val < list2->val)
{
cur->next = list1;
list1 = list1->next;
}
else
{
cur->next = list2;
list2 = list2->next;
}
cur = cur->next;
}
if(list1)
{
cur->next = list1;
}
if(list2)
{
cur->next = list2;
}
//return dummy.next;
return dummy->next;
}
};