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

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

你传入的参数是两个python自带的list,并不是你自定义的链表,必须先将list中每个值都用链表存起来,再调用addTwoNumbers函数