leetcode-AddTwoNum

AddTwoNum

You are given two linked lists representing two non-negative numbers. 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.

example

Input: (2 -> 4 -> 3) + (5 -> 6 -> 4)
Output: 7 -> 0 -> 8

思路

  思路不算复杂,就是按照我们正常的加法竖式计算的方式来完成此题就可以。需要注意的细节有两点:

  1. 进位值
  2. 判断list结尾

  关于进位值(程序中定义为extra变量)在本题中,如果是list最后两个数字相加的进位,往往会被忽略。第二点,两个list不一定是等长的,所以在遍历的过程中,需要对list结尾进行判断,防止运行时空指针错误。注意这两点,可能就可以正确完成本题了。

coding

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
#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 result(0);
ListNode* tempResult = &result;
int l1Value, l2Value, extra;
l1Value = l2Value = extra = 0;
while(l1 != NULL || l2 != NULL || extra != 0)
{
l1Value = (l1!=NULL)?l1->val : 0;
l2Value = (l2!=NULL)?l2->val : 0;
tempResult->next = new ListNode((l1Value+l2Value+extra)%10);
extra = (l1Value+l2Value+extra) / 10;
l1 != NULL ? l1 = l1->next : l1 = NULL;
l2 != NULL ? l2 = l2->next : l2 = NULL;
tempResult = tempResult->next;
}
return result.next;
}
};
int main(int argc, char *argv[])
{
ListNode* l1 = new ListNode(2);
l1->next = new ListNode(4);
l1->next->next = new ListNode(3);
ListNode* l2 = new ListNode(5);
l2->next = new ListNode(6);
l2->next->next = new ListNode(4);
//l2->next->next = new ListNode(7);
Solution s;
ListNode* result = s.addTwoNumbers(l1,l2);
while(result)
{
cout << result->val << endl;
result = result->next;
}
return 0;
}

github

github代码链接

------ 本文结束 ------
扫二维码
扫一扫,用手机访问本站

扫一扫,用手机访问本站

发送邮件