第一题:两数相加(Medium)
环境:python3,力扣官网
题目:
给你两个 非空 的链表,表示两个非负的整数。它们每位数字都是按照 逆序 的方式存储的,并且每个节点只能存储 一位 数字。请你将两个数相加,并以相同形式返回一个表示和的链表。你可以假设除了数字 0 之外,这两个数都不会以 0 开头。
题解:
解法一:
# 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:
if l1 == None:
return l2
if l2 == None:
return l1
dumy = ListNode(0)
cur =dumy
carry = 0
while l1 and l2:
cur.next = ListNode((l1.val+l2.val+carry)%10)
carry = (l1.val+l2.val +carry)//10
l1 = l1.next
l2 =l2.next
cur =cur.next
if l2:
while l2:
cur.next = ListNode((l2.val+carry)%10)
carry = (l2.val +carry)//10
l2 =l2.next
cur =cur.next
if l1:
while l1:
cur.next=ListNode((l1.val+carry)%10)
carry =(l1.val+carry)//10
l1=l1.next
cur=cur.next
if carry==1:
cur.next =ListNode(1)
return dumy.next