/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode() : val(0), next(nullptr) {}
* ListNode(int x) : val(x), next(nullptr) {}
* ListNode(int x, ListNode *next) : val(x), next(next) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* res=new ListNode();
ListNode* ref=res;
stack<int> n1;
stack<int> n2;
stack<int> ans;
int c=0;
while(l1 || l2)
{
if(l1!=nullptr)
{
n1.push(l1->val);
l1=l1->next;
}
if(l2!=nullptr)
{
n2.push(l2->val);
l2=l2->next;
}
}
while(!n1.empty() || !n2.empty() || c)
{
if(!n1.empty())
{
c+=n1.top();
n1.pop();
}
if(!n2.empty())
{
c+=n2.top();
n2.pop();
}
ans.push(c%10);
c/=10;
}
while(!ans.empty())
{
ref->next = new ListNode(ans.top());
ans.pop();
ref=ref->next;
}
return res->next;
}
};Please feel free to ask if any doubt.
Upvote if you liked it!!!!!!