数字相加¶
两个数字用链表存储,给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4)
输出:7 -> 0 -> 8
原因:342 + 465 = 807
这个是leetcode上面的真题
代码实现如下:
# Definition for singly-linked list.
class ListNode:
def __init__(self, x):
self.val = x
self.next = None
class Solution:
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
l3 = ListNode(0)
tmp1 = l1
tmp2 = l2
tmp3 = l3
pre_tmp3 = l3
while(tmp1!=None or tmp2!=None):
if(tmp1!=None and tmp2!=None):
tmp3.val = tmp1.val + tmp2.val +tmp3.val
tmp1 = tmp1.next
tmp2 = tmp2.next
elif(tmp1!=None):
tmp3.val = tmp1.val +tmp3.val
tmp1 = tmp1.next
else:
tmp3.val = tmp2.val +tmp3.val
tmp2 = tmp2.next
if(tmp3.val>=10):
tmp3.val=tmp3.val-10;
tmp3.next = ListNode(1)
else:
tmp3.next = ListNode(0)
pre_tmp3 = tmp3
tmp3 = tmp3.next
if(tmp3.val==0):
pre_tmp3.next = None
return l3
def showNumbers(self, l1):
while(l1 != None):
print(l1.val, end=" ")
l1 = l1.next
print("")
return
def ListNodeList(self, *args):
l = ListNode(0)
tmp = l
size = len(args)
for i in range(size-1):
tmp.val = args[i]
tmp.next = ListNode(0)
tmp = tmp.next
tmp.val = args[size-1]
return l
if __name__ == '__main__':
s = Solution()
l1 = s.ListNodeList(2, 4, 3)
s.showNumbers(l1)
l2 = s.ListNodeList(5, 6, 4)
s.showNumbers(l2)
l3 = s.addTwoNumbers(l1, l2)
s.showNumbers(l3)
l4 = s.addTwoNumbers(l2, l3)
s.showNumbers(l4)
在完成代码之后对计算结果输出进行简单验证。