/*
LeetCode_0023
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
*/
struct ListNode {
int val ;
ListNode *next;
ListNode(int x) : val (x), next(NULL) {}
};
1. 以递归的方式
ListNode* mergeTwo(ListNode* l1, ListNode* l2) {
if (l1 == NULL )
return l2;
if (l2 == NULL )
return l1;
if (l1-> val <= l2-> val) {
l1-> next = mergeTwo(l1-> next, l2);
return l1;
}
if (l1-> val > l2-> val) {
l2-> next = mergeTwo(l1, l2-> next);
return l2;
}
}
2. 直接合并
ListNode* mergeTwo(ListNode* l1, ListNode* l2) {
ListNode dummy(- 1 );
ListNode* result = & dummy;
while (l1&& l2) {
if (l1-> val <= l2-> val) {
result-> next = l1;
result = result-> next;
l1 = l1-> next;
}
else if (l1-> val > l2-> val) {
result-> next = l2;
result = result-> next;
l2 = l2-> next;
}
}
while (l1)
result-> next = l1;
while (l2)
result-> next = l2;
return dummy. next;
}
3. 合并k个有序链表
ListNode *mergeKLists(vector <ListNode *> &lists) {
if (lists.empty()) {
return nullptr ;
}
while (lists.size() > 1 ) {
lists.push_back(mergeTwoLists(lists[0 ], lists[1 ]));
lists.erase(lists.begin());
lists.erase(lists.begin());
}
return lists.front();
}
ListNode *mergeKLists(vector <ListNode *> &lists) {
if (lists.empty()) return NULL;
int len = lists.size();
while (len > 1 )
{
for (int i = 0 ; i < len / 2 ; ++i)
{
lists[i] = mergeTwoLists(lists[i], lists[len - 1 - i]);
}
len = (len + 1 ) / 2 ;
}
return lists.front();
}