[英]How do I remove a node from a linked list?
As a first project on OOP I'm working on a linked list oop class, got most of the methods done but the remove node method is not working. 作为OOP上的第一个项目,我正在开发一个链表oop类,完成了大部分方法,但删除节点方法不起作用。 When I run the code I get this error: 当我运行代码时,我收到此错误:
AttributeError: 'Node' object has no attribute 'val' AttributeError:'Node'对象没有属性'val'
I can't figure out what I'm doing wrong in it! 我无法弄清楚我做错了什么!
class Node():
def __init__(self, val):
self.value = val
self.next = None
class Linked_list():
def __init__(self):
self.next = None
nextnode=self.next
def insert(self, val, loc):
p = self
for i in range(0, loc):
p = p.next
tmp = p.next
newNode = Node(val)
p.next = newNode
newNode.next = tmp
def find(self, val):
p = self.next
# loc = 0 # in case we want to return the location
while p != None:
if p.value == val:
return p
else:
p = p.next
#loc=loc+1 # in case we want to return the location
return None
def remove_node(self, node):
current = self.next
previous = None
found = False
while not found:
if current.val == node:
found = True
else:
previous = current
current = current.next
if previous == None:
self.next = current.next
else:
previous.current.next
def __eq__(self, other):
cnt=0
s=self.next
p=other.next
if Linked_list.length(self)!=Linked_list.length(other):
return False
if s.value==p.value:
for i in range(Linked_list.length(self)-1):
p=p.next
s=s.next
if s.value==p.value:
cnt+=1
if cnt==Linked_list.length(self)-1:
return True
else:
return False
Your Node
class has an attribute value
assigned in the __init__
method, but not an attribute val
, hence the error. 您的Node
类具有在__init__
方法中指定的属性value
,但不是属性val
,因此是错误。 The confusion probably comes from the fact that the variable you pass to __init__
is called val
. 混淆可能来自于传递给__init__
的变量称为val
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.