剑指offer----合并两个升序链表

/*
struct ListNode {
	int val;
	struct ListNode *next;
	ListNode(int x) :
			val(x), next(NULL) {
	}
};*/
//非递归写法
class Solution1 {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2){
        if(!pHead2)
            return pHead1;
        if(!pHead1)
            return pHead2;
        ListNode *min = NULL;
        if(pHead1->val < pHead2->val)
        {
            min = pHead1;
            pHead1 = pHead1->next;
        }
        else
        {
            min = pHead2;
            pHead2 = pHead2->next;
        }
        ListNode * head = min;
        while(pHead1!= NULL && pHead2 != NULL)
        {
            if(pHead1->val < pHead2->val)
            {
                min->next = pHead1;
                pHead1 = pHead1->next;
            }
            else
            {
                min ->next = pHead2;
                pHead2 = pHead2->next;
            }
            min = min ->next;
        }
        if(pHead1 !=NULL)
            min->next   = pHead1;
        if(pHead2 !=NULL)
            min->next   = pHead2;
        return head;
    }
};
//递归写法
class Solution {
public:
    ListNode* Merge(ListNode* pHead1, ListNode* pHead2){
        if(pHead2 == NULL)
            return pHead1;
        if(pHead1 == NULL)
            return pHead2;
        if(pHead1->val < pHead2->val)
        {
            pHead1->next = Merge(pHead1->next,pHead2);
            return pHead1;
        }
        else
        {
            pHead2->next = Merge(pHead1,pHead2->next);
            return pHead2;
        }
    }
};

猜你喜欢

转载自blog.csdn.net/run32875094/article/details/80201048