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

链表相加(二)

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

# class ListNode:
#     def __init__(self, x):
#         self.val = x
#         self.next = None
#
# 代码中的类名、方法名、参数名已经指定,请勿修改,直接返回方法规定的值即可
#
# 
# @param head1 ListNode类 
# @param head2 ListNode类 
# @return ListNode类
#
class Solution:
    def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
        l1 = []
        l2 = []
        l3 = []
        h1 = head1
        h2 = head2
        while h1 or h2:
            if h1:
                l1.append(h1.val)
                h1 = h1.next
            if h2:
                l2.append(h2.val)
                h2 = h2.next
        advance = 0
        while l1 or l2:
            n1 = 0
            n2 = 0
            if l1:
                n1 = l1.pop()
            if l2:
                n2 = l2.pop()
            l3.append((n1+n2+advance)%10)
            advance = ((n1+n2+advance)//10)
        if advance > 0:
            l3.append(advance)
        head = ListNode(l3.pop())
        cur = head
        while l3:
            cur.next = ListNode(l3.pop())
            cur = cur.next
        return head

全部评论

相关推荐

不愿透露姓名的神秘牛友
01-07 00:20
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

更多
牛客网
牛客网在线编程
牛客网题解
牛客企业服务