您的位置:首页 > 其它

Merge k Sorted Lists

2016-07-08 09:36 190 查看


23. Merge k Sorted Lists



 



Merge k sorted linked lists and return it as one sorted list. Analyze and describe its complexity.

Subscribe to see which companies asked this question

思路:进行 lists.size() 次合并俩个有序链表


/**
* 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) {
ListNode *ans=new ListNode(0);
for(int i=0;i<lists.size();i++){
ListNode *cur_ans=ans->next;
ListNode *cur_answer=new ListNode(0);
ListNode *cur=cur_answer;
while(cur_ans && lists[i]){
if(lists[i]->val<cur_ans->val){
cur->next=lists[i];
lists[i]=lists[i]->next;
cur=cur->next;
}
else{
cur->next=cur_ans;
cur_ans=cur_ans->next;
cur=cur->next;
}

}
if(lists[i]){
cur->next=lists[i];
}
if(cur_ans){
cur->next=cur_ans;
}
ans->next=cur_answer->next;
}
return ans->next;
}
};






内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  LeetCode 链表