Merge k Sorted Lists

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




posted on 2016-07-08 09:36  胖胖的乓乓  阅读(119)  评论(0编辑  收藏  举报

导航