题解 | 链表相加(二)

链表相加(二)

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

from operator import ne
import re
from pickle import NONE
# 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, head1:ListNode):
        #采用头插法反转列表
        newList = None
        cur = head1
        while(cur):
            next = cur.next
            cur.next = newList
            newList = cur
            cur = next
        # 这里的意思是,newList他不知道是否为ListNode,因为如果不走循环,那么他就是None
        return newList
    
    def addInList(self , head1: ListNode, head2: ListNode) -> ListNode:
        # write code here
        newList1 = self.reverseList(head1)
        newList2 = self.reverseList(head2)
        carry = 0
        p = newList1
        q = newList2
        resList = None
        if (newList1 is None and newList2 is None):
            return newList2
        while(p or q or carry):
            value1 = p.val if p else 0
            value2 = q.val if q else 0
            total = value1 + value2 + carry
            carry = total // 10
            value = total %  10
            newNode = ListNode(value)
            newNode.next = resList
            resList = newNode
            if p: p = p.next
            if q: q = q.next
        return resList




            



    

出现的问题 1.在循环体用到head 2. 忘记指针移动 3.调用成员函数要用self. 4.指针移动的前提是指针存在 5.成员函数的使用

全部评论
点赞 回复 分享
发布于 02-27 11:41 广东

相关推荐

06-26 10:08
门头沟学院 C++
北京Golang实习,一个月4700,吃住都不报,公司位置在海淀。请问友友怎么看呢?如果要租房的话有什么建议吗
码农索隆:租房肯定是合租了,剩下的钱,差不多够正常吃饭了,看看能不能学到东西吧
点赞 评论 收藏
分享
06-02 15:17
门头沟学院 Java
心爱的idea:怎么会呢 应该是打招呼有问题 问就说实习6个月全国可飞随时到岗
点赞 评论 收藏
分享
每晚夜里独自颤抖:把华北改为华南再试一试,应该就没啥问题了。改完可能都不用投,别人主动联系了。
点赞 评论 收藏
分享
评论
1
收藏
分享

创作者周榜

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