在python3函数中传递参数时出错



我正在python 3.7.7中编写一个链表程序为此,我创建了两个名为NodeLinked List的类。

class Node:
def __init__(self, data):
self.data = data
self.next = None

节点类包含每个节点的结构,即它有2个属性。链表类包含以下函数:

class LinkedList:
# UTILITY FUNCTIONS
# Function to push a node
def lpush(head_ref, new_data):
# allocate node
new_node = Node(new_data)
new_node.next = head_ref
head_ref = new_node
return head_ref
# Function to print linked list
def lprint(node):
count = 0
while node != None:
print(node.data, end=" ")
node = node.next
count = count + 1

在驱动程序函数中,我正在创建一个node类的节点(头(对象,其值为-1。

head = Node(-1)

我创建了一个LinkedList类的对象,名为Llist

llist = LinkedList()

现在,我正试图通过调用lpush((函数将值插入到链表中

for i in range(20, 0, -1):
head = llist.lpush(head, i)

但它抛出了以下错误。

> Traceback (most recent call last):
File "/home/subham-brc/Python-3.7.3/Python Files/Linked List/8.py", line 79, in <module>
head = llist.lpush(head, i)
TypeError: lpush() takes 2 positional arguments but 3 were given

非常感谢您的帮助。。

您需要将self作为第一个参数添加到lpushlprint中,即使您没有使用它。无论何时在LinkedList对象上调用方法,都会简单地提供这些参数。

最新更新