47ms easy to understand C++ solution


  • 0
    Y
    /**
     * 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) {
            int remain = 0;
            int lengthL1 = 0;
            int lengthL2 = 0;
            ListNode* _l1 = l1;
            ListNode* _l2 = l2; 
            // decide which one is longer
            while(true){
                if(_l1 != NULL){
                    ++lengthL1;
                    _l1 = _l1 -> next;
                }
                if(_l2 != NULL){
                    _l2 = _l2 -> next;
                    ++lengthL2;
                }
                if(_l1 == NULL && _l2 == NULL) break;
            }
            // always make l1 the longer one
            if(lengthL1 < lengthL2){
                ListNode *tmp = l1;
                l1 = l2;
                l2 = tmp;
            }
            // reset pointers
            _l1 = l1;
            _l2 = l2;
            // in case that we need to insert at the tail
            ListNode* _preL1;
            while(_l1 != NULL){
                if(_l2 != NULL)
                    _l1->val += ( _l2 -> val + remain );
                else
                    _l1 -> val += remain;
                remain = _l1 -> val / 10;
                _l1 -> val = _l1 -> val % 10;
                _preL1 = _l1;
                _l1 = _l1 -> next;
                if( _l2 != NULL)
                    _l2 = _l2 -> next;
            }
            if(remain != 0)
                 _preL1 -> next = new ListNode(remain);
            return l1;
            
        }
    };
    
    

Log in to reply
 

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