题解 | #链表相加(二)#

链表相加(二)

https://www.nowcoder.com/practice/c56f6c70fb3f4849bc56e33ff2a50b6b


#思路:链表反转,然后相加,然后再反转回来
class Solution:
    def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
        def revers(head: ListNode):
            dummy = None
            cur = head
            while cur:
                temp = cur.next
                cur.next = dummy
                dummy = cur
                cur = temp
            return dummy 
        head1 = revers(head1)
        cur = head1
        head2 = revers(head2)
        b = 0
        while head1 and head2:
            a = (head1.val + head2.val+b) % 10 
            b = (head1.val + head2.val+b) // 10
            head1.val = a
            pre = head1
            head1 = head1.next
            head2 = head2.next
            
        if head1 and not head2:
            if head1.val +b < 10:
                head1.val = (head1.val + b)
            else:
                if head1.next == None:
                    head1.next =  ListNode((head1.val + b)//10)

                else:
                    head1.next.val = (head1.val + b)//10 + head1.next.val
                head1.val = (head1.val + b)%10

        if head2 and not head1:
            pre.next = head2
            if head2.val +b < 10:
                head2.val = (head2.val + b)
            else:
                if head2.next == None:
                    head2.next =  ListNode((head2.val + b)//10)
                else:
                    head2.next.val = head2.next.val + (head2.val + b)//10
                head2.val = (head2.val + b)%10
        if not head1 and not head2:
            if b > 0:
                head1 = ListNode(b)
        return revers(cur)



        
        # write code here

全部评论

相关推荐

点赞 评论 收藏
分享
09-25 13:56
门头沟学院 Java
V进厂倒计时:直接外包给你还不要出钱,完美
点赞 评论 收藏
分享
在校生实习:我觉得平时学校肯定有各种大作业吧。包装一下写项目里。特长那块喧宾夺主了,项目肯定是大头。特长里比如:熟悉vscode,这个感觉不具有吸引性。简要介绍你会什么语言,什么工具等就行了。同26找实习,我是个超级菜鸡😭大家一起加油
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务