LeetCode-合并两个有序链表(递归方法+非递归)

/**
 * Definition for singly-linked list.
 * struct ListNode {
 *     int val;
 *     ListNode *next;
 *     ListNode(int x) : val(x), next(NULL) {}
 * };

 */

//递归法:不断将每次较小的数链接起来;

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1==NULL)
            return l2;
        if(l2==NULL)
            return l1;
        if((l1->val)>(l2->val))
        {
            ListNode *ptr=l2; 
            ptr->next=mergeTwoLists(l1, l2->next);
            return ptr;
        }
        else
        {
            ListNode *ptr=l1;
            ptr->next=mergeTwoLists(l1->next, l2);
            return ptr;
        }
    }

};

//非递归:cur不断移动,将各个节点链接

class Solution {
public:
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2) {
        if(l1==NULL)
            return l2;
        if(l2==NULL)
            return l1;
        if(l2==NULL&&l1==NULL)
            return NULL;
        ListNode* cur=new ListNode(0);
        ListNode* newList=cur;
        while(l1!=NULL&&l2!=NULL)
        {
            if(l1->val>l2->val)
            {
                cur->next=l2;
                l2=l2->next;
            }
            else
            {
                cur->next=l1;
                l1=l1->next;
            }
            cur=cur->next;           
        }
        if(l1==NULL)
            cur->next=l2;
        else
            cur->next=l1;
        return newList->next;
    }
};

猜你喜欢

转载自blog.csdn.net/kiss__soul/article/details/79874062