Dynamic Memory Allocation problem in C++


  • 0
    P
        /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        int AddRecursion(ListNode* List1, ListNode* List2, ListNode* List3)
        {
            int Carry = 0;
            int sum;
            if ((List1->next != NULL) || (List2->next != NULL))
            {
                List3->next = new ListNode(0);
                Carry = AddRecursion(List1->next, List2->next, List3->next);
            }
            sum = List1->val + List2->val + Carry;
            List3->val = sum > 9 ? sum%10 : sum;
            return (sum > 9 ? 1 : 0);
        }
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode* l3 = new ListNode(0);
            ListNode* List3 = l3;
            AddRecursion(l1->next, l2->next, List3);
            /*if (!AddRecursion(l1, l2, l3))
            {
                l3->val = 1;
                l3->next = NULL;
            }
            else
                l3->next = NULL;*/
            return List3;
        }
        
    };
    
    I am creating dynamic memory in addTwoNumbers function and passing to AddRecursion function.
    

    Inside AddRecursion the new node is being created and linked.
    But once the control is back to addTwoNumbers function the list has only one element.
    Can someone help me out with this.


Log in to reply
 

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