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

为什么定义了链表类还是报错'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日

悬赏问题

  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效
  • ¥15 悬赏!微信开发者工具报错,求帮改