gpt4 book ai didi

Python 堆叠链表

转载 作者:太空宇宙 更新时间:2023-11-03 14:54:47 24 4
gpt4 key购买 nike

一切似乎都可以使用下面的代码,但是我不断收到此错误:

Attribute 'next' defined outside init (attribute-defined-outside-init)` at temp.next = self.head (in the push function)

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

class Stack(object):
def __init__(self):
self.head = None

def push(self, item):
temp = Node(item)
temp.next = self.head
self.head = temp

def pop(self):
if self.head is None:
raise IndexError("Can't pop from empty stack.")
else:
current = self.head
self.head = current.next
return current.data

def peek(self):
if self.head is None:
raise IndexError("Can't peek at empty stack.")
else:
return self.head.data

最佳答案

您的初始化函数不正确。

而不是

def __init__(self, initdata):
self.data = initdata
self.next_node = None

应该是

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

关于Python 堆叠链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45665270/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com