[leetcode]两数相加


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本身

一.python代码

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
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
q=l1
p=l2
hum=ListNode(0)
w=hum
tag=0
while (q or p):
if q!=None:
x=q.val
q=q.next
else:
x=0
if p!=None:
y=p.val
p=p.next
else:
y=0
sum=((x+y+tag)%10)
if ((x+y+tag)>9):
tag=1
else:
tag=0
w.next=ListNode(sum)
w=w.next
if tag==1:
w.next=ListNode(tag)
return hum.next

二.C++

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
/**
* 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) {
int sum;
int tag=0;

ListNode *num=new ListNode(0);

ListNode *w = num;


while (l1||l2)
{
int x;
int y;
if (l1)
{
x = l1->val;
l1 = l1->next;
}
else
x = 0;
if (l2)
{
y = l2->val;
l2 = l2->next;
}
else
y = 0;
sum = (x+y+tag)%10;
if ((x + y + tag) >= 10) tag = 1;
else
tag = 0;
/*ListNode* pnew = new ListNode(sum);*/

w->next = new ListNode(sum);
w = w->next;
/* w->next = pnew;
w = pnew;*/
}
/*if (tag==1) w->next = new ListNode(tag);*/
if (tag == 1)
{
ListNode* pnew = new ListNode(tag);
w->next = pnew;
}
return num->next;
}
};

链表

将一个链表赋值给另一个,他们的next地址指向永远相同。
调用一个链表的next,就是将链表后面所有的都打印出来。
链表一定要赋值了,才有next的地址,不然链表的next就是空。