My straightforward and easy-to-understand C++ solution


  • -1
    D
    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
            // this solution looks like merging two sorted links, 
            // just adding processing of potential carries
    
            if(!l1) return l2;
            if(!l2) return l1;
            
            ListNode *p = l1, *q = l2;
            ListNode *head = new ListNode(0); // our list has a head node, thus return head->next
            ListNode *tail = head;            // use tail to construct new list.
            
            int cf = 0, cur_val = 0;          // cf means Carry Flag!
            
            while(p&&q){
                cur_val = p->val+q->val+cf;
                ListNode *tmp = new ListNode(cur_val);
                
                if(cur_val>= 10) {cf = 1; tmp->val -= 10;}
                else cf = 0;
    
                tail->next = tmp; tail = tail->next;
                p = p->next; q = q->next;
            }
            while(p){ // if l1 is longer than l2
                cur_val = p->val + cf;
                ListNode *tmp = new ListNode(cur_val);
                
                if(cur_val>=10) {cf = 1; tmp->val -= 10;}
                else cf = 0;
    
                tail->next = tmp; tail = tail->next;
                p = p->next;
            }
            while(q){ // if l2 is longer than l1
                cur_val = q->val+cf;
                ListNode *tmp = new ListNode(cur_val);
                if(cur_val>= 10){ cf = 1; tmp->val -= 10; }
                else cf = 0;
    
                tail->next = tmp; tail = tail->next;
                q = q->next;
            }
            if(cf){ // something like "999 + 1"
                ListNode *tmp = new ListNode(1);
                tail->next = tmp;
            }
            return head->next;
        }

Log in to reply
 

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