Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路:这和merge两个数组思维一样,通过一个辅助链表将比较的两个链表中较小的数存起来,最终得到结果。把每次得到的新链表存在lists的最后,并且去除lists中比较的两个链表,当lists的大小为1是,lists[0]就是我们想要的结果。
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode * merge(ListNode *a, ListNode *b) {
ListNode *answer = new ListNode(0);
ListNode *temp = answer;
if (a == NULL) {
return b;
}
if (b == NULL) {
return a;
}
while (a != NULL && b != NULL) {
if (a -> val < b -> val) {
answer -> next = a;
a = a -> next;
answer = answer -> next;
} else {
answer -> next = b;
b = b -> next;
answer = answer -> next;
}
}
while (a != NULL) {
answer -> next = a;
a = a -> next;
answer = answer -> next;
}
while (b != NULL) {
answer -> next = b;
b = b -> next;
answer = answer -> next;
}
return temp -> next;
}
class Solution {
public:
ListNode* mergeKLists(vector<ListNode*>& lists) {
if (lists.size() == 1) {
return lists[0];
}
if (lists.size() == 0) {
return NULL;
}
lists.push_back( merge(lists[0], lists[1]) );
lists.erase(lists.begin(), lists.begin() + 2);
return mergeKLists(lists);
}
};