【问题标题】:TypeError: __init__() missing 1 required positional argument: 'head' my compiler is giving error at line 51TypeError: __init__() missing 1 required positional argument: \'head\' 我的编译器在第 51 行给出错误
【发布时间】:2022-11-03 01:21:20
【问题描述】:

我正在尝试在 python 中学习链表。这是一个非常简单的代码。我在这里要做的就是调用一个类的构造函数。但这给了我一个错误。它在说:

#This is the code I have written please help me resolve this problem
class node:
    def __init__(self,data):
        self.data=data
        self.next=None
class linkedlist:
    def __init__(self,head):
        self.head=None
    def insertathead(self,data):
        newnode=node(data)
        if(self.head==None):
            self.head=newnode
        else:
            newnode.next=self.head
            self.head=newnode
    def insertatend(self,data):
        newnode=node(data)
        if(self.head==None):
            self.head=newnode
        else:
            temp=self.head
            while(temp.next!=None):
                temp=temp.next
            temp.next=newnode
    def insert(self,position,data):
        newnode=node(data)
        count=1
        if(self.head==None):
            self.head=newnode
        elif(position==1):
            newnode.next=self.head
            self.head=newnode 
        else:
            while(temp.next!=None):
                if(count==position):
                    break
                else:
                    prev=temp
                    temp=temp.next
                    count=count+1
        prev.next=newnode
        newnode.next=temp
    def printlist(self):
        if(self.head==None):
            print("your list is empty")
        else:
            temp=self.head
            while(temp.next!=None):
                print(temp,end=' ')
                temp=temp.next               

mylist=linkedlist()
mylist.insertathead(25)
mylist.printlist

File "D:\roug1.py", line 51, in <module>
    mylist=linkedlist()
TypeError: __init__() missing 1 required positional argument: 'head'

这是我的编译器给出的错误。我不知道该怎么做。谁能给我正确的代码

【问题讨论】:

    标签: python data-structures linked-list singly-linked-list


    【解决方案1】:

    这里的问题是您正在调用不带参数的链表构造函数:

     mylist=linkedlist()
    

    而在类定义中,它有一个位置参数“head”:

    class linkedlist:
        def __init__(self, head):
    

    要修复错误,您需要向构造函数提供“head”参数,例如

    mylist=linkedlist(node('Head'))
    

    【讨论】:

      【解决方案2】:

      您需要为 LinkedList 类的头部传入一个实际节点:linkedlist(Node)

      您的在里面LinkedList 的 (self, head) 方法需要 head 参数,我假设它是一个节点。所以,当你实例化对象时,你需要给它一个你想要作为“头”节点的引用

      前任。

      head_node = Node(25)
      mylist=linkedlist(head_node)
      
      # now do whatever you want
      mylist.insertathead(25)
      mylist.printlist
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2018-05-19
        • 2016-05-09
        • 2020-09-27
        • 1970-01-01
        • 2022-01-06
        • 2023-03-28
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多