首页 > 代码库 > 【Leetcode长征系列】Merge k Sorted Lists
【Leetcode长征系列】Merge k Sorted Lists
原题:
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了…
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。