Merge k Sorted Lists

来源:互联网 发布:有好看衣服的淘宝店铺 编辑:程序博客网 时间:2024/05/20 09:44

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;    }};




1 0