# 2. Add Two Numbers

## 1.問題&#x20;

* 給予兩個linked list, 數值以反的順序儲存, 每個node只有一個數字, 將兩個list相加並回傳新的list

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LHxT8MrOYCl2pLRWCzV%2F-LHxV4rFBXWBSBm2eElD%2F201872107.jpg?alt=media\&token=c5e7ba14-aa3a-4a36-a4ed-d495b885cdce)

## 2.想法&#x20;

* 1.Create新的ListNode來儲存相加後兩節點的值

```
ListNode  head(0), * p = &head;
```

* 2.走訪串列

```
while (l1 || l2 || cast) {
    int sum = l1 + l2 + cast;
    int value = sum % 10;
    int cast = sum / 10;
    p->next = new ListNode(value);
    p = p->next;
    l1 = l1? l1->next : l1;
    l2 = l2? l2->next : l2;
}
```

* 3.回傳

```
p = &head;
return head->next
```



## 3.程式碼

```
/**
 * 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 preHead(0),*p = &preHead;
        int extra=0,sum=0;
        while( l1 || l2 || extra){
            sum= (l1 ? l1->val : 0) + (l2 ? l2->val : 0) + extra;
            extra = sum / 10;
            p->next = new ListNode(sum % 10);
            p = p->next;
            l1 = l1? l1->next : l1;
            l2 = l2? l2->next : l2;
        }
        p = &preHead;
        return p->next;       
    }
};
```

## 4.Performance

![](https://901207480-files.gitbook.io/~/files/v0/b/gitbook-legacy-files/o/assets%2F-LGKoChvN9am4__HCIRK%2F-LHxT8MrOYCl2pLRWCzV%2F-LHxW0KDp-NEiAmUAYun%2F201872108.jpg?alt=media\&token=4a87d5e5-e290-4382-a234-c5de0e131353)
