# [leetcode] Add Two Numbers

### Add Two Numbers

You are given two linked lists representing two non-negative numbers. 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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

tags: linked list, math

9.21.2015update

There is a cleaner solution with fewer codes.

```/**
* 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 dummyHead = ListNode(0);
ListNode * p1 = l1, * p2 = l2;
ListNode * q = &dummyHead;//BUG HERE
int carry = 0;
while(p1 != NULL || p2 != NULL){
int x = (p1 != NULL)? p1->val: 0;
int y = (p2 != NULL)? p2->val: 0;
int sum = x + y + carry;
carry = sum / 10;
sum = sum % 10;
q->next = new ListNode(sum);
q = q->next;
p1 = (p1 != NULL)? p1->next: NULL;
p2 = (p2 != NULL)? p2->next: NULL;
}
if(carry > 0){
q->next = new ListNode(carry);
}
}
};```

swap范例：

```    ListNode *swap(ListNode *l){
ListNode * p, * n;
if(l->next == NULL){
return l;
}
else{
p = l;
l = l->next;
p->next = NULL;
while(l != NULL){
n = l->next;
l->next = p;
p = l;
l = n;
}
}
return p;
}```

```/**
* 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 *add(ListNode *l1, ListNode *l2){
int sum = 0;
int overflow = 0;
ListNode * p = NULL;
ListNode * tail = NULL;
ListNode * l = NULL;
while(l1 != NULL && l2 != NULL){
sum  = l1->val + l2->val + overflow;
overflow = sum / 10;
sum = sum % 10;
if(p == NULL){
p = tail = new ListNode(sum);
}
else{
tail->next = new ListNode(sum);
tail = tail->next;
}
l1 = l1->next;
l2 = l2->next;
}
if(l1 != NULL){
l = l1;
}
else if(l2 != NULL){
l = l2;
}
while(l != NULL){
sum = l->val + overflow;
overflow = sum / 10;
sum = sum % 10;
if(p == NULL){
p = tail = new ListNode(sum);
}
else{
tail->next = new ListNode(sum);
tail = tail->next;
}
l = l->next;
}
if(overflow != 0){
tail->next = new ListNode(overflow);
overflow = 0;
tail = tail->next;
}
return p;
}
};```

This site uses Akismet to reduce spam. Learn how your comment data is processed.