多个有序的链表合并

/**
 * 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 * pRes = NULL;
        for(int i=0; i<lists.size(); i++)
        {
            pRes = mergeTwoLists(pRes, lists[i]);
        }
        return pRes;
    }
    ListNode* mergeTwoLists(ListNode * list1, ListNode * list2)
    {
        if(list1 == NULL && list2 == NULL)
            return NULL;
        else if(list1 == NULL)
            return list2;
        else if(list2 == NULL)
			return list1;
        ListNode * pLast = new ListNode(0);
        
        ListNode * pres = new ListNode(0);
        pLast = pres;
        while(list1 != NULL && list2 != NULL)
        {
            if(list1->val > list2->val)
            {
                pres->next = list2;
                list2 = list2->next;
                pres = pres->next;
                pres->next = NULL;
            }
            else
            {
                pres->next = list1;
                list1 = list1->next;
                pres = pres->next;
                pres->next = NULL;
            }
        }
        if(list1 != NULL)
        {
            pres->next = list1;
        }
        if(list2 != NULL)
        {
            pres->next = list2;
        }
        return pLast->next;        
    }
};

 

展开阅读全文

没有更多推荐了,返回首页