Sekika 2022-10-18 15:02 采纳率: 50%
浏览 475
已结题

为什么定义了链表类还是报错'list' object has no attribute 'val'

问题遇到的现象和发生背景

为什么定义了链表类还是报错


'list' object has no attribute 'val'
用代码块功能插入代码,请勿粘贴截图
from typing import Optional
# Definition for singly-linked list.


class ListNode:
    def __init__(self, val=0, next=None):
        self.val = val
        self.next = next


class Solution:
    def addTwoNumbers(self, l1: ListNode, l2: ListNode) -> ListNode:
        head = ListNode(l1.val+l2.val)
        current = head
        while l1.next and l2.next:
            l1 = l1.next
            l2 = l2.next
            current.next = ListNode(l1.val+l2.val+current.val//10)
            current.val = current.val % 10
            current = current.next
        if l1.next == None and l2.next:
            while l2.next:
                l2 = l2.next
                current.next= ListNode(l2.val+current.val//10)
                current.val = current.val % 10
                current = current.next
                current.next = l2.next
        elif l2.next == None and l1.next:
            while l1.next:
                l1 = l1.next
                current.next= ListNode(l1.val+current.val//10)
                current.val = current.val % 10
                current = current.next
                current.next = l2.next
        if current.val >= 10:
            current.next = ListNode(current.val//10)
            current.val = current.val % 10
        return head


l1 = [2, 4, 3]
l2 = [5, 6, 4]
a = Solution()
print(a.addTwoNumbers(l1, l2))

运行结果及报错内容

"E:\python project\venv\Scripts\python.exe" "E:\python project\两数相加.py"
Traceback (most recent call last):
File "E:\python project\两数相加.py", line 46, in
print(a.addTwoNumbers(l1, l2))
File "E:\python project\两数相加.py", line 14, in addTwoNumbers
head = ListNode(l1.val+l2.val)
AttributeError: 'list' object has no attribute 'val'

  • 写回答

2条回答 默认 最新

  • 於黾 2022-10-18 15:22
    关注

    你的l1和l2也必须是链表啊,你为什么要传列表

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

问题事件

  • 系统已结题 10月26日
  • 已采纳回答 10月18日
  • 创建了问题 10月18日

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵