You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
I did find the answer to this problem on net but I wanted help with figuring out what is wrong with my code. I also know my code is not the best in regards to optimization but any help is accepted.
/**
* 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 *p=l1, *q=l2;
ListNode *sum= nullptr, *lastdigit= nullptr;
int num1=0,num2=0;
while(p!= nullptr)
{
int val1= p->val;
num1=(10*num1)+val1;
p=p->next;
}
cout<<num1<<endl;
while(q!=nullptr)
{
int val2 = q->val;
num2 =(10*num2)+val2;
q=q->next;
}
cout<<num2<<endl;
int sum_=num1+num2;
int r= sum_%10;
sum= new ListNode(r);
sum_/=10;
lastdigit = sum;
while(sum_!=0)
{
int r= sum_%10;
lastdigit->next= new ListNode(r);
lastdigit=lastdigit->next;
sum_/=10;
}
return sum;
}
};
3->2->1->null, but you're converting this to 321. (This storage convention makes the expected solution easier to implement).