# LeetCode2. Add Two Numbers（链表 / 模拟）

## 2019 年 01 月 26 日 • 阅读: 900 • LeetCode • 阅读设置

• Medium
• Accepted：726,574
• Submissions：2,401,046

### Description

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.

### 代码

• Runtime: 24 ms, faster than 91.94% of C++ online submissions for Add Two Numbers.
/**
* struct ListNode {
*     int val;
*     ListNode *next;
*     ListNode(int x) : val(x), next(NULL) {}
* };
*/
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2) {
ListNode* ans = new ListNode(-1); // 结果链表“表头”
ListNode* tmp = ans; // 临时链表指针
int carry = 0, a1, a2, sum;
while (l1 || l2)
{
a1 = l1 ? l1->val : 0; // 为空则为0
a2 = l2 ? l2->val : 0;
sum = a1 + a2 + carry;
carry = sum / 10; // 进位
tmp->next = new ListNode(sum % 10); // 当前位
tmp = tmp->next; // 指针后移
if (l1)
l1 = l1->next;
if (l2)
l2 = l2->next;
}
if (carry) // 考虑最后的进位
tmp->next = new ListNode(1);
return ans->next;
}
};

### 拓展

// “tmp和ans指向的是同一个玩意”
int main()
{
ListNode* ans = new ListNode(-1);
ListNode* tmp = ans;
cout << ans->val << endl; // -1
cout << tmp->val << endl; // -1
cout << ans << endl; // 0xaa0de8
cout << tmp << endl; // 0xaa0de8
cout << &ans << endl; // 0x6efeec
cout << &tmp << endl; // 0x6efee8
ans->next = new ListNode(1);
ans = ans->next;
cout << ans->val << endl; // 1
cout << tmp->next->val << endl; // 1
return 0;
}

The end.

2019年1月26日 星期六