# Add Two Numbers II in C++

C++Server Side ProgrammingProgramming

Suppose we have two non-empty linked lists representing two non-negative integers. Here the most significant digit comes first and each of their nodes contain a single digit. We have to adf the two numbers and return it as a linked list. So if the lists are [7, 2, 4, 3] + [5, 6, 4], then the result will be [7, 8, 0, 7]

To solve this, we will follow these steps −

• Create a node called dummy, and store value 0, create stacks s1 and s2.

• fill s1 by the nodes of l1 and fill s2 by the nodes of s2.

• sum := 0

• while s1 is not empty or s2 is not empty

• if s1 is empty, then sum := sum + top value of s1, delete from stack s1

• if s2 is empty, then sum := sum + top value of s2, delete from stack s2

• value of dummy := sum mod 10

• new node := create a new node with the value sum/10

• next of new node := dummy

• dummy := new node

• sum := sum / 10

• if dummy value is 0, then return next of dummy, otherwise dummy.

## Example (C++)

Let us see the following implementation to get a better understanding −

Live Demo

#include <bits/stdc++.h>
using namespace std;
class ListNode{
public:
int val;
ListNode *next;
ListNode(int data){
val = data;
next = NULL;
}
};
ListNode *make_list(vector<int> v){
for(int i = 1; i<v.size(); i++){
while(ptr->next != NULL){
ptr = ptr->next;
}
ptr->next = new ListNode(v[i]);
}
}
cout << "[";
while(ptr){
cout << ptr->val << ", ";
ptr = ptr->next;
}
cout << "]" << endl;
}
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* dummy;
dummy = new ListNode(0);
stack <ListNode*> s1, s2;
while(l1){
s1.push(l1);
l1 = l1->next;
}
while(l2){
s2.push(l2);
l2 = l2->next;
}
int sum = 0;
while(!s1.empty() || !s2.empty()){
if(!s1.empty()){
sum += s1.top()->val;
s1.pop();
}
if(!s2.empty()){
sum += s2.top()->val;
s2.pop();
}
dummy->val = (sum % 10);
ListNode* newNode = new ListNode(sum / 10);
newNode->next = dummy;
dummy = newNode;
sum /= 10;
}
return dummy->val == 0? dummy->next : dummy;
}
};
main(){
vector<int> v1 = {7,2,4,3};
ListNode *h1 = make_list(v1);
vector<int> v2 = {5,6,4};
ListNode *h2 = make_list(v2);
Solution ob;
}
[7,2,4,3]
[5,6,4]
[7, 8, 0, 7, ]