2. 两数相加(Add Two Numbers)
给你两个非空的链表,表示两个非负的整数。它们每位数字都是按照逆序的方式存储的,并且每个节点只能存储一位数字。
请你将两个数相加,并以相同形式返回一个表示和的链表。
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
You are given two non-empty linked lists representing two non-negative integers. The digits are stored in reverse order, and each of their nodes contains a single digit. Add the two numbers and return the sum as a linked list.
You may assume the two numbers do not contain any leading zero, except the number 0 itself.
示例 1:
输入:l1 = [2,4,3], l2 = [5,6,4]
输出:[7,0,8]
解释:342 + 465 = 807
示例 2:
输入:l1 = [0], l2 = [0]
输出:[0]
示例 3:
输入:l1 = [9,9,9,9,9,9,9], l2 = [9,9,9,9]
输出:[8,9,9,9,0,0,0,1]
提示:
每个链表中的节点数在范围 [1, 100] 内
0 <= Node.val <= 9
题目数据保证列表表示的数字不含前导零
题解一(python):
#Definition for singly-linked list.
#class ListNode:
#def __init__(self, val=0, next=None):
#self.val = val
#self.next = next
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
#取出两个链表的数值
s1 = ''
while l1 is not None:
s1 = s1 + str(l1.val)
l1 = l1.next
s2 = ''
while l2 is not None:
s2 = s2 + str(l2.val)
l2 = l2.next
#两个链表的值相加求和
s3 = int(s1[::-1]) + int(s2[::-1])
s3 = [int(i) for i in str(s3)][::-1]
#创建新链表
#root作为根节点
root = ListNode(s3.pop(0))
#current指针用于创建接下来的节点
current = root
while s3 != []:
current.next = ListNode(s3.pop(0))
current = current.next
return root