给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
代码实现:
# Definition for singly-linked list.
# class ListNode:
# def __init__(self, x):
# self.val = x
# self.next = None
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
val_sum = l1.val + l2.val
list_node = ListNode(val_sum % 10)
a = val_sum // 10
node = list_node
while True:
try:
l1 = l1.next
except:
pass
try:
l2 = l2.next
except:
pass
if not l1 and not l2:
break
elif not l1:
l1_val = 0
l2_val = l2.val
elif not l2:
l2_val = 0
l1_val = l1.val
else:
l1_val = l1.val
l2_val = l2.val
val_sum = l1_val + l2_val + a
temp_node = ListNode(val_sum % 10)
node.next = temp_node
node = temp_node
a = val_sum // 10
if a != 0:
node.next = ListNode(a)
return list_node
注:这是在网上做的练习题,记录一下,有需要的时候方便自己查看。