0%

#2 Add Two Numbers

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:

1
2
3
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
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
/**
* 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 *p=l1,*q=l2; // 工作指针
int carry = 0; // 进位
ListNode *l3=new ListNode(-1); // 头结点
ListNode *r=l3; // l3的工作指针
int temp;

while (p||q){
if(p&&q){
temp = p->val + q->val + carry;
carry = temp/10;
ListNode *node=new ListNode(temp%10);
r->next = node;
r = node;
p = p->next;
q = q->next;
}

if(p&&!q){
temp = p->val + carry;
carry = temp/10;
ListNode *node=new ListNode(temp%10);
r->next = node;
r = node;
p = p->next;
}

if(!p&&q){
temp = q->val + carry;
carry = temp/10;
ListNode *node=new ListNode(temp%10);
r->next = node;
r = node;
q = q->next;
}
}

if(carry>0){
ListNode *node=new ListNode(carry);
r->next = node;
r = node;
}
return l3->next;
}
};