[recommend for beginners]clean C++ implementation with detailed explaination


  • 2

    This problem is all about details.

    I do think you should implement it quickly considering all the corner cases.

    The 2 key points are

       -1-    deal with the linked-list  rest points considering the carry number
    

    the second is

       -2-    consider the final carry number !
    

    Here is my implementation .

     class Solution {
        public:
            ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
                ListNode *dummy=new ListNode(-1), *cur=dummy;
                int carry=0;
                while(l1 && l2){
                    int cur_val = (l1->val + l2->val + carry);
                    carry = cur_val/10;
                    ListNode* temp=new ListNode(cur_val%10);
                    cur->next = temp;
                    cur = cur->next;
                    l1=l1->next;
                    l2=l2->next;
                }
                //
                if(l1){
                    while(l1){
                        int cur_val = (l1->val + carry);
                        carry = cur_val/10;
                        ListNode* temp=new ListNode(cur_val%10);
                        cur->next = temp;
                        cur = cur->next;
                        l1=l1->next;
                    }
                }
                if(l2){
                    while(l2){
                        int cur_val = (l2->val + carry);
                        carry = cur_val/10;
                        ListNode* temp=new ListNode(cur_val%10);
                        cur->next = temp;
                        cur = cur->next;
                        l2=l2->next;
                    }
                }
                
                if(carry){
                    ListNode* temp=new ListNode(carry);
                    cur->next=temp;
                }
                
                return dummy->next;
            }
        };

Log in to reply
 

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