0%

两数相加(中等)

题目要求:

给出两个 非空 的链表用来表示两个非负的整数。其中,它们各自的位数是按照 逆序 的方式存储的,并且它们的每个节点只能存储 一位 数字。(在这个题目中链表连起来的数字与实际数字反序)

如果,我们将这两个数相加起来,则会返回一个新的链表来表示它们的和。

您可以假设除了数字 0 之外,这两个数都不会以 0 开头。

示例:

输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因: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
56
57
58
59
60
61
62
63
/**
* 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 len1=1;
int len2=1;
ListNode *l3=new ListNode(-1);
ListNode *p=l1;
ListNode *q=l2;
while (p->next!=NULL){
len1+=1;
p=p->next;
}
while (q->next!=NULL){
len2+=1;
q=q->next;
}
if (len1<len2){
int tmp=len2-len1;
for (int i=0;i<tmp;i++){
p->next=new ListNode(0);
p=p->next;
}
}
else{
int tmp=len1-len2;
for (int i=0;i<tmp;i++){
q->next=new ListNode(0);
q=q->next;
}
}
p=l1;
q=l2;
bool count=false;
int tmp=0;
ListNode *w=l3;
while (p!=NULL&&q!=NULL){
tmp=p->val+q->val+count;
if (tmp>=10){
count=true;
tmp=tmp%10;
}
else{
count=false;
}
w->next=new ListNode(tmp);
w=w->next;
p=p->next;
q=q->next;
}
if (count==true){
w->next=new ListNode(1);
}
return l3->next;
}
};
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
# Definition for singly-linked list.

# class ListNode:

# def __init__(self, x):

# self.val = x

# self.next = None


class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
a1=[]
a2=[]
while l1:
a1.append(l1.val)
l1=l1.next
while l2:
a2.append(l2.val)
l2=l2.next
s1=''
for i in range(len(a1)-1,-1,-1):
s1=s1+str(a1[i])
s2=''
for j in range(len(a2)-1,-1,-1):
s2=s2+str(a2[j])
#字符串转成整数
m1=int(s1)
m2=int(s2)
#整数之和转成字符串
m3=str(m1+m2)
#新建两个空链表
tmp_node=ListNode(None)
node=ListNode(None)
#从后往前遍历和字符串,插入链表
for x in m3[::-1]:
#print(x)
if not tmp_node.val:
tmp_node.val=x
node=tmp_node
#print(node)
else:
tmp_node.next=ListNode(x)
tmp_node=tmp_node.next

return node

python与c++的解法思路不同,c++在于直接将链表中的每个数字相加,在后面判断是否有进位。而python则是通过语言优势,将两个链表中的数字收集到了数组中,再各自加入到字符串中,然后直接转化而为数字,就不用再判断进位了,从而直接转化为一个新的结果链表