两数相加(链表逆序)

在这里插入图片描述
正常加法逻辑。

# Definition for singly-linked list.
# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None

class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        if not l1:
            return l2
        if not l2:
            return l1
        a=l1.val+l2.val
        re=ListNode(a%10)
        l=re        
        while l1.next and l2.next:
            l1,l2=l1.next,l2.next            
            i=a//10
            a=l1.val+l2.val+i
            l.next=ListNode(a%10)
            l=l.next 
        i=a//10           

        if not l1.next:            
            while l2.next:
                l2=l2.next
                a=l2.val+i
                l.next=ListNode(a%10)
                i=a//10
                l=l.next
        if not l2.next:
            while l1.next:
                l1=l1.next
                a=l1.val+i
                l.next=ListNode(a%10)
                i=a//10
                l=l.next
        if i:
            l.next=ListNode(1)
        return re

在这里插入图片描述

发布了115 篇原创文章 · 获赞 0 · 访问量 2106

猜你喜欢

转载自blog.csdn.net/weixin_45569078/article/details/104687824
今日推荐