首页 技术 正文
技术 2022年11月20日
0 收藏 885 点赞 4,427 浏览 1411 个字

题目:

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.

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

代码:

该题目其实就是链表中的数字取出来,然后相加,不过注意高位数字在后面,需要倒过来。比如题目例子中就是要:342+465=807,之后把807每一位从小到大记录在一个链表里。

于是,我用了最常规的办法,不过也是解决了问题的:

#coding:utf-8
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = Noneclass Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
if not l1 and not l2:return
#取出链表中的数字存入数组
arr1,arr2=[],[]
while l1:
arr1.append(l1.val)
l1 = l1.next
while l2:
arr2.append(l2.val)
l2 = l2.next
#倒序
arr1.reverse()
arr2.reverse()
#print (arr1,arr2)
#组成数字
num1,num2 = 0,0
for i in arr1:
num1 = num1*10+i
for i in arr2:
num2 = num2*10+i
print (num1,num2)
#相加
num_total = num1+num2
print (num_total)
#从低位到高位写入链表,初始化链表的根节点为0,如果相加的和为0,直接返回
l_res = ListNode(0)
cursor = l_res
if num_total == 0: return l_res
while num_total:
temp = num_total%10
print (temp)
cursor.next = ListNode(temp)
cursor = cursor.next
num_total = int(num_total/10)
#print (num_total)
return l_res.nextif __name__=='__main__':
#创建l1和l2两个链表,注意,排序好的就需要arr1和arr2中数字从小到大
arr1 = [0,8,6,5,6,8,3,5,7]
arr2 = [6,7,8,0,8,5,8,9,7]
l1 = ListNode(arr1[0])
p1 = l1
l2 = ListNode(arr2[0])
p2 = l2
for i in arr1[1:]:
p1.next = ListNode(i)
p1 = p1.next
for i in arr2[1:]:
p2.next = ListNode(i)
p2 = p2.next
s=Solution()
#两个链表相加
q=s.addTwoNumbers(l1,l2)

一些打印的输出:

753865680 798580876
1552446556
6
5
5
6
4
4
2
5
5
1
相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,948
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,474
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,287
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,102
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,734
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,769