题解 | #链表相加(二)#反转-相加-进位

链表相加(二)

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 reverseList(self,head:ListNode):
        if head==None:
            return None
        '''
        cur,pre=head,None
        while cur:
            b=cur.next
            cur.next=pre
            pre=cur
            cur=b
        return pre'''
        a,a.next,b=head,None,head.next  # 初始化
        while b: # 当b非空时
            b,a,a.next=b.next,b,a       # 遍历
        return a
    
    def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
        # write code here
        # 有至少一个空链表时
        if not head1:
            return head2
        if not head2:
            return head1
        # 两个链表均不为空时
        # 先反转
        head1=self.reverseList(head1)
        head2=self.reverseList(head2)
        # 创建一个空链表
        res=ListNode(-1)
        head=res
        # 填充空列表
        carry=0 # 进位
        while head1 or head2 or carry: 
        # 当n1 n2有1个不为空时(可能有一个为空)
            val1=0 if not head1 else head1.val
            val2=0 if not head2 else head2.val
            a=val1+val2+carry
            carry=(int)(a/10)
            a=a%10 # 两值之和,除以10的余数
            head.next=ListNode(a)
            head=head.next
            if head1:
                head1=head1.next  # 当n1为空时,不再移动
            if head2:
                head2=head2.next  # 当n2为空时,不再移动
        
        return self.reverseList(res.next)







        

全部评论

相关推荐

27届毕业,最近想找一段大厂实习,感觉简历有些问题,好多都不给面,求大佬们指点,最近好焦虑
重生之我学Java干...:我从后端的角度分析一下你的第一个项目,我感觉亮点不是很突出。因为我是因为组内有需求,临时上手学react干活。我用到的技术基本就cover你那个智慧园区管理平台的很多亮点了。那作为比较专业的前端,你上述的内容是不是有点单薄呢。感觉还得包装
点赞 评论 收藏
分享
10-10 16:30
济宁学院 Java
一表renzha:面试官:蓝桥杯三等奖?你多去两次厕所都能拿二等吧
点赞 评论 收藏
分享
酷酷的喜马拉雅山:感觉这比一直在初筛不动的好多了
点赞 评论 收藏
分享
评论
点赞
收藏
分享

创作者周榜

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