原题:
Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.
思路:两条两条地合并。时间复杂度为O(n),n为所有链表节点和。
代码:
/**
* 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 NULL;
if(lists.size()==1) return lists[0];
ListNode *res;
stack<ListNode*> now;
int i = 0;
ListNode *tmp1, *tmp2;
now.push(lists[0]);
now.push(lists[1]);
i+=2;
while(i<lists.size()){
tmp1 = now.top();
now.pop();
tmp2 = now.top();
now.pop();
res = mergeTwo(tmp1,tmp2);
if(i>=lists.size()) break;
now.push(res);
now.push(lists[i]);
i++;
}
return res;
}
ListNode *mergeTwo(ListNode* former, ListNode* later){
if(former==NULL && later!=NULL) return later;
if(later==NULL && former!=NULL) return former;
if(former==NULL && later==NULL) return NULL;
ListNode *tmp = former, *tmp2 = later, *res, *head = NULL;
if(tmp->val <= tmp2->val) {
head = tmp;
tmp = tmp->next;
}
else {
head = tmp2;
tmp2 = tmp2->next;
}
res = head;
while(tmp && tmp2){
if(tmp->val>tmp2->val) {
res->next = tmp2;
tmp2 = tmp2->next;
}
else {
res->next = tmp;
tmp = tmp->next;
}
res =res->next;
}
if(tmp!=NULL) res->next = tmp;
if(tmp2!=NULL) res->next = tmp2;
return head;
}
};
但是RE了…
==========================================================================================================================================
while(i<lists.size())
改成
while(i<=lists.size())
AC了=。=