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 contain a single digit. Add the two numbers and return it as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
Example
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) Output: 7 -> 0 -> 8 Explanation: 342 + 465 = 807.
#include<iostream>
using namespace std;
struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
int num1[100] = {0};
int num2[100] = {0};
int num3[100] = {0};
int i = 0, j = 0, k = 0;
int flag = 0;
while(l1 != NULL){
num1[i] = l1 ->val;
l1 = l1 ->next;
i++;
}
while(l2 != NULL){
num2[j] = l2 ->val;
l2 = l2 ->next;
j++;
}
while((i > 0) || (j > 0) || (flag == 1)){
num3[k] = num1[k] + num2[k] + flag;
if(num3[k] > 9){
num3[k] = num3[k] - 10;
flag = 1;
}else flag = 0;
i--;
j--;
k++;
}
i = 0;
ListNode* n = new ListNode(num3[i]);
ListNode* l3 = n;
i++;
while(i < k){
n ->next = new ListNode(num3[i]);
n = n ->next;
i++;
}
return l3;
}
};
int main()
{
Solution a;
ListNode* pnode;
ListNode* p1 = new ListNode(2);
ListNode* p2 = new ListNode(4);
ListNode* p3 = new ListNode(3);
p1 ->next = p2;
p2 ->next = p3;
ListNode* m1 = new ListNode(5);
ListNode* m2 = new ListNode(6);
ListNode* m3 = new ListNode(4);
m1 ->next= m2;
m2 ->next = m3;
pnode = a.addTwoNumbers(p1, m1);
cout << "pnode0 = "<< pnode->val << endl;
pnode = pnode ->next;
cout << "pnode1 = "<< pnode->val << endl;
pnode = pnode ->next;
cout << "pnode2 = "<< pnode->val << endl;
system("pause");
return 0;
}