My C++ solution


  • 0
    F
    class Solution {
    public:
        ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            ListNode *head; 
            ListNode *current = new ListNode(0);
            head = current;
            int cary = 0;
            
            while(l1 || l2){
                current->val = cary;
                if(l1){
                  current->val += l1->val;
                  l1 = l1->next;
                }
                if(l2){ 
                    current->val += l2->val;
                    l2 = l2->next;
                }                  
                cary = current->val/10;
                current->val %= 10;
                if(l1 || l2 || cary > 0){
                   current->next = new ListNode(cary);
                   current = current->next;
                }
            }
            return head;
        }
    };
    

Log in to reply
 

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