My solution, just loop


  • 0
    D
    /**
     * 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) {
        ListNode *ret;
        ListNode *tmp,*l1_prev,*l2_prev;
    
        if(l1==NULL&&l2==NULL)
            return NULL;
        else if(l2==NULL&&l1!=NULL)
            ret=l1;
        else if(l2!=NULL && l1==NULL)
            ret=l2;
        else if(l1->val<=l2->val)
            ret=l1;
        else
            ret=l2;
            
            
        while(l1!=NULL && l2!=NULL)
        {
        if(l1->val<=l2->val)
            {
            if(l1->next==NULL||l1->next->val>l2->val)
                {
                tmp=l1;
                l1=l1->next;
                tmp->next=l2;
                }
            else
                l1=l1->next;
            
            }
        else
            {
            if(l2->next==NULL||l2->next->val>=l1->val)
                {
                tmp=l2;
                l2=l2->next;
                tmp->next=l1;
                }
            else
                l2=l2->next;            
            }
        }   
        
        return ret;
    }
    

    };


Log in to reply
 

Looks like your connection to LeetCode Discuss was lost, please wait while we try to reconnect.