You are giventwo linked lists representing two non-negative numbers. The digits are storedin reverse order and each of their nodes contain a single digit. Add the twonumbers and return it as a linked list.
Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8
/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode *addTwoNumbers(ListNode *l1, ListNode *l2) {
ListNode *p = new ListNode(0);
ListNode *head = p;
int c=0;
while (l1 || l2) {
p->next = new ListNode(0);
p = p->next;
if (l1){
p->val += l1->val;
l1 = l1->next;
}
if (l2) {
p->val += l2->val;
l2 =l2->next;
}
p->val += c;
if (p->val>9){
p->val -= 10;
c = 1;
} else {
c = 0;
}
}
if (c) {
p->next = new ListNode(1);
}
p = head->next;
delete head;
head = p;
return head;
}
};