Iterative solution


  • 0
    R

    """
    ListNode* mergeTwoLists(ListNode* l1, ListNode* l2)
    {
    ListNode *it1 = l1;
    ListNode *it2 = l2;
    ListNode *rethead = NULL;
    ListNode *ret = NULL;

        while (NULL != it1 && NULL != it2)
        {
            if (NULL == ret)
            {
                ret = new ListNode(0);
                rethead = ret;
            }
            else
            {
                ret->next = new ListNode(0);
                ret = ret->next;
            }   
            if (it1->val < it2->val)
            {
                ret->val = it1->val;
                it1 = it1->next;
            }
            else
            {
                ret->val = it2->val;
                it2 = it2->next;
            }
        }
        while (NULL != it1)
        {
            if (NULL == ret)
            {
                ret = new ListNode(0);
                rethead = ret;
            }
            else
            {
                ret->next = new ListNode(0);
                ret = ret->next;
            }   
            ret->val = it1->val;
            it1 = it1->next;
        }
        while (NULL != it2)
        {
            if (NULL == ret)
            {
                ret = new ListNode(0);
                rethead = ret;
            }
            else
            {
                ret->next = new ListNode(0);
                ret = ret->next;
            }   
            ret->val = it2->val;
            it2 = it2->next;
        }
        return rethead;
    }
    

    """


Log in to reply
 

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