链表的合并

/**
 * 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 *head=NULL;
         size_t size=lists.size();
         if(size<=0){
             return head;
         }
         for(int i=0;i<size;i++){
             head=mergelist(head,lists[i]);
         }
         return head;
        
    }
    ListNode *mergelist(ListNode * &h1,ListNode * &h2) {
        if(h1==NULL){
            return h2;
        }else if(h2==NULL){
            return h1;
        }
        ListNode *realhead;
        if(h1->val<h2->val){
            realhead=h1;
            realhead->next=mergelist(h1->next,h2);
        }else{
            realhead=h2;
            realhead->next=mergelist(h1,h2->next);
        }
        return realhead;
    }
        

};

猜你喜欢

转载自blog.csdn.net/u010325193/article/details/86322704