合并k个排序链表

样例

给出3个排序链表[2->4->null,null,-1->null],返回 -1->2->4->null

标签   Expand  

/**
 * Definition of ListNode
 * class ListNode {
 * public:
 *     int val;
 *     ListNode *next;
 *     ListNode(int val) {
 *         this->val = val;
 *         this->next = NULL;
 *     }
 * }
 */
class Solution {
public:
    /**
     * @param lists: a list of ListNode
     * @return: The head of one sorted list.
     */
    ListNode *merge2Lists(ListNode* a,ListNode* b){
        if(a==NULL) return b;
        if(b==NULL) return a;
        ListNode *dummy=new ListNode(-1);
        ListNode *tmp=dummy;
        while(a&&b){
            if(a->val<=b->val){
                tmp->next=a;
                a=a->next;
            }else{
                tmp->next=b;
                b=b->next;
            }
            tmp=tmp->next;
        }
        if(a) tmp->next=a;
        if(b) tmp->next=b;
        return dummy->next;
        
    }
    ListNode *mergeKLists(vector &lists) {
        // write your code here
        int n=lists.size();
        ListNode* res=NULL;
        if(n==0) return NULL;
        if(n==1) return lists[0];
        for(int i=0;i


你可能感兴趣的:(算法与数据结构)