给定两个非空链表来表示两个非负整数。位数按照逆序方式存储,它们的每个节点只存储单个数字。将两数相加返回一个新的链表。
你可以假设除了数字 0 之外,这两个数字都不会以零开头。
示例:
输入:(2 -> 4 -> 3) + (5 -> 6 -> 4) 输出:7 -> 0 -> 8 原因:342 + 465 = 807
Python3:
# Definition for singly-linked list.
class ListNode(object):
def __init__(self, x):
self.val = x
self.next = None
class Solution(object):
def addTwoNumbers(self, l1, l2):
"""
:type l1: ListNode
:type l2: ListNode
:rtype: ListNode
"""
num1 = ''
num2 = ''
while l1:
num1 += str(l1.val)
l1 = l1.next
while l2:
num2 += str(l2.val)
l2 = l2.next
num3 = int(num1[::-1]) + int(num2[::-1])
l3_head = None
tmp = None
str_num3 = str(num3)[::-1]
return [int(x) for x in str_num3]
# for num in str_num3:
# l3 = ListNode(int(num))
# if tmp is not None:
# tmp.next = l3
# tmp = l3
# if num == str_num3[0]:
# l3_head = l3
# return l3_head
l1 = ListNode(2)
l11 = ListNode(4)
l12 = ListNode(3)
l1.next = l11
l11.next = l12
l2 = ListNode(5)
l21 = ListNode(6)
l22 = ListNode(4)
l2.next = l21
l21.next = l22
solution = Solution()
l3 = solution.addTwoNumbers(l1, l2)
return_list = []
# tmp_l3 = l3
# while tmp_l3:
# return_list.append(tmp_l3.val)
# tmp_l3 = tmp_l3.next
print(l3)