Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
Example:
Input:
[
1->4->5,
1->3->4,
2->6
]
Output: 1->1->2->3->4->4->5->6
/**
* 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)
{
if(lists.empty()) return nullptr ;
ListNode* res = nullptr ;
while(lists.size() > 1)
{
auto list1 = lists.back() ;
lists.pop_back() ;
auto list2 = lists.back() ;
lists.pop_back() ;
res = mergeTwoLists(list1 , list2) ;
lists.insert(lists.begin() , res) ;
}
res = lists.back() ; //要考虑到lists大小为1的情况
return res ;
}
private :
ListNode* mergeTwoLists(ListNode* p1 , ListNode* p2)
{
ListNode dummy(-1) ;
ListNode* last = &dummy ;
while(p1 != NULL && p2 != NULL)
{
if(p1->val < p2->val)
{
last->next = p1 ;
p1 = p1->next ;
last = last->next ;
}
else
{
last->next = p2 ;
p2 = p2->next ;
last = last->next ;
}
}
if(p2 != NULL)
{
last->next = p2 ;
}
else if(p1 != NULL)
{
last->next = p1 ;
}
return dummy.next ;
}
};
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* reverseKGroup(ListNode* head, int k)
{
ListNode header(-1) ;
header.next = head ;
ListNode *prev = &header , *suf = prev->next;
for(int i = 1 ; suf ; ++i)
{
if(i % k == 0)
{
prev = reverse(prev , suf->next) ;
suf = prev->next ;
}
else
{
suf = suf->next ;
}
}
return header.next ;
}
private :
ListNode* reverse(ListNode* prev , ListNode* suf)
{
ListNode *last = prev->next , *cur = last->next ;//继续犯复合类型定义的错误。。。
while(cur != suf)
{
last->next = cur->next ;
cur->next = prev->next ;
prev->next = cur ;
cur = last->next ;
}
return last ;
}
};