very easy to understand code using stack with runtime 29 ms.


  • 0
    F

    This code uses stack to store the digits in each list, then build the new list using digits in the two stack

    ListNode* addTwoNumbers(ListNode* l1, ListNode* l2){
    	stack<int> digits1, digits2;
    
    	while (l1){
    		digits1.push(l1->val);
    		l1 = l1->next;
    	}
    	while (l2){
    		digits2.push(l2->val);
    		l2 = l2->next;
    	}
    
    	ListNode* head = nullptr;
    	ListNode* current = nullptr;
    
    	int carry = 0;
    	while (!digits1.empty() || !digits2.empty() ||carry){
    		int val1 = 0, val2 = 0;
    		if (!digits1.empty()){
    			val1 = digits1.top();
    			digits1.pop();
    		}
    		else
    			val1 = 0;
    
    		if (!digits2.empty()){
    			val2 = digits2.top();
    			digits2.pop();
    		}
    		else
    			val2 = 0;
    
    		int sum = val1 + val2 + carry;
    		carry = sum / 10;
    
    		current = new ListNode(sum % 10);
    		current->next = head;
    		head = current;
    	}
    
    	return head;
    }
    

Log in to reply
 

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