两数相加
1,程序简介
-
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。
-
请你将两个数相加,并以相同形式返回一个表示和的链表。
-
你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
示例 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
- 题目数据保证列表表示的数字不含前导零
2,程序代码
# -*- coding: utf-8 -*-
"""
Created on Fri Jan 7 18:58:42 2022
Function: 两数相加
@author: 小梁aixj
"""
class ListNode:
def __init__(self, val=0, next=None):
self.val = val
self.next = next
class LinkList:
def __init__(self):
self.head=None
def initList(self, data):
self.head = ListNode(data[0])
r=self.head
p = self.head
for i in data[1:]:
node = ListNode(i)
p.next = node
p = p.next
return r
def convert_list(self,head):
ret = []
if head == None:
return
node = head
while node != None:
ret.append(node.val)
node = node.next
return ret
class Solution:
def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
lrr = l1
while True:
l1.val = l1.val + l2.val
if l1.next is None and l2.next is None and l1.val < 10:
break
if l1.next is None:
l1.next = ListNode(0)
if l2.next is None:
l2.next = ListNode(0)
if l1.val >= 10:
l1.val = l1.val - 10
l1.next.val += 1
l1 = l1.next
l2 = l2.next
return lrr
# %%
l = LinkList()
list1 = [2,4,3]
list2 = [5,6,4]
l1 = l.initList(list1)
l2 = l.initList(list2)
s = Solution()
print(l.convert_list(s.addTwoNumbers(l1, l2)))