# 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)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jenhsuan.gitbook.io/algorithm/leetcode/2.-add-two-numbers.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
