logo头像

往者不可谏,来者犹可追。

LeetCode_problem_2_Add_Two_Numbers

问题描述

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.

假定两个数都不是0开头,除了数本身就是0。


例子

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


思路

题目没什么难点,就是链表的顺序遍历问题。注意进位就行了,可能最后有一个进位要再创建一个节点,不要漏掉。


代码

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
/**
* C++ 代码
* 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 head(-1);
int f = 0; //标识进位
ListNode* pre = &head;
ListNode* pa = l1, *pb = l2;
int val = 0, a, b;
while(pa!=nullptr||pb!=nullptr){

a = pa == nullptr?0:pa->val;
b = pb == nullptr?0:pb->val;
val = a + b + f;
f = val / 10;
val = val % 10;

pre->next = new ListNode(val);

pa=pa==nullptr?nullptr:pa->next;
pb=pb==nullptr?nullptr:pb->next;
pre = pre->next;
}
//最后判断是否有进位
if(f>0){
pre->next = new ListNode(f);
}
return head.next;
}
};
上一篇