1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93

#include <iostream>

/*
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.

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4) --> 342 + 465
Output: 7 -> 0 -> 8 --> result == 807
*/

/**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/

struct ListNode {
int val;
ListNode *next;
ListNode(int x) : val(x), next(NULL) {} //构造函数
};

class Solution {
public:
static ListNode* addTwoNumbers(ListNode* l1, ListNode* l2);
};

using namespace std;

//题目没有明确说明两个list的长度相等
ListNode* Solution::addTwoNumbers(ListNode* l1,ListNode* l2)
{
if(NULL == l1 || NULL == l2){
return nullptr;
}

bool carry = false; //进位标志
auto left = l1,right = l2;
auto ret = new ListNode(0);
auto ret_head = ret; //记录第一个节点,即为list头

do{
ret->val = left->val + right->val;
if(carry){
ret->val += 1; //进位标志只提供一进位而没有更多进位,因为题目要求并不会出现相加后大于二十,因此进位最多为1
carry = false;
}
if(ret->val >= 10){
ret->val -= 10;
carry = true;
}
left = left->next;
right = right->next;
ret->next = new ListNode(-1); //构造下一节点
ret = ret->next; //让当前节点指向下一节点
}while(left != nullptr && right != nullptr);

return ret_head; //返回list的头结点
}

int main()
{ /*注意:题目要求list中每一个node的值都是一个digital,即每个节点出现的数值为[-9,-9]*/
ListNode* x1 = new ListNode(2);
ListNode* x2 = new ListNode(4);
ListNode* x3 = new ListNode(3);
x1->next = x2;
x2->next = x3;
x3->next = nullptr;

ListNode* y1 = new ListNode(5);
ListNode* y2 = new ListNode(6);
ListNode* y3 = new ListNode(4);
y1->next = y2;
y2->next = y3;
y3->next = nullptr;

auto ret = Solution::addTwoNumbers(x1,y1);
for(;ret != nullptr && ret->val > -1;ret = ret->next){
cout << ret->val << "-";
}
cout<<endl;

return 0;
}