2.两数相加--python

题目:两个非空链表表示两个非负整数,逆序保存,将两链表表示的数相加,返回一个新的逆序链表

法:两数加法,只是用链表逆序表示,注意:1)考虑进位,尤其是最后一次的进位;2)每次移动指针,避免陷入死循环

 def addTwoNumbers(self, l1, l2):
        if l1==None:return l2
        if l2==None:return l1
        
        p,q=l1,l2
        res=ListNode(0)
        head,carry=res,0
        while p!=None or q!=None:
            tmp=0
            if p:
                tmp+=p.val
                p=p.next
            if q:
                tmp+=q.val
                q=q.next
            tmp+=carry
            carry=tmp//10
            tmp%=10
            head.next=ListNode(tmp)
            head=head.next
        
        if carry:
            head.next=ListNode(carry)
        return res.next
                

猜你喜欢

转载自blog.csdn.net/karen17/article/details/88878924
今日推荐