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

链表相加(二)

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

全部评论

相关推荐

点赞 评论 收藏
分享
球球别再泡了:坏,我单9要了14
点赞 评论 收藏
分享
点赞 收藏 评论
分享
牛客网
牛客企业服务