c++ solution


  • 0
    W

    what a stupid question - here's a nasty hack solution.

    /**
     * Definition for singly-linked list.
     * struct ListNode {
     *     int val;
     *     ListNode *next;
     *     ListNode(int x) : val(x), next(NULL) {}
     * };
     */
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) 
        {
            ListNode* ll1=l1;
            ListNode* last_l1;
            int carryover=0;        
            while(l1)
            {
                int n=l1->val + (l2?l2->val:0) + carryover;
                l1->val = n %10;
                carryover = n/10;           
    
                if(!l1->next && l2)
                {
                    l1->next=l2->next;
                    l2=nullptr;
                }
                
                last_l1=l1;
                l1=l1->next;
                l2=l2?l2->next:nullptr;
            }
            if(carryover)
                last_l1->next = new ListNode(carryover);
            
            return ll1;
        }
    };
    

Log in to reply
 

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