#include <iostream>
using namespace std;
struct ListNode {
int val;
ListNode* next;
ListNode(int x) : val(x), next(NULL) {}
};
class Solution {
public:
ListNode* addTwoNumbers(ListNode* l1, ListNode* l2)
{
ListNode* dummy = new ListNode(0);
ListNode* p = dummy;
int carry = 0; // 定义进位值
while (l1 || l2 || carry)
{
int sum = carry;
if (l1)
{
sum += l1->val;
l1 = l1->next;
}
if (l2)
{
sum += l2->val;
l2 = l2->next;
}
carry = sum / 10;
p->next = new ListNode(sum % 10);
p = p->next;
}
return dummy->next;
}
};
int main() {
// 创建两个链表:1->2->3 和 4->5->6
ListNode* l1 = new ListNode(3);
l1->next = new ListNode(2);
l1->next->next = new ListNode(1);
ListNode* l2 = new ListNode(6);
l2->next = new ListNode(5);
l2->next->next = new ListNode(4);
Solution solution;
// 相加两个链表
ListNode* res = solution.addTwoNumbers(l1, l2);
// 输出结果链表的值
while (res) {
cout << res->val << " ";
res = res->next;
}
cout << endl;
return 0;
}
05-20
654
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
03-04
2975
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
01-05
337
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
06-30
1259
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)
02-15
4452
![](https://csdnimg.cn/release/blogv2/dist/pc/img/readCountWhite.png)