Python 如何从链接列表中删除节点?
作为OOP上的第一个项目,我正在处理一个链表OOP类,完成了大多数方法,但remove node方法不起作用。 运行代码时,出现以下错误: AttributeError:“节点”对象没有属性“val” 我想不出我做错了什么Python 如何从链接列表中删除节点?,python,class,oop,error-handling,linked-list,Python,Class,Oop,Error Handling,Linked List,作为OOP上的第一个项目,我正在处理一个链表OOP类,完成了大多数方法,但remove node方法不起作用。 运行代码时,出现以下错误: AttributeError:“节点”对象没有属性“val” 我想不出我做错了什么 class Node(): def __init__(self, val): self.value = val self.next = None class Linked_list(): def __init__(self)
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
您的
节点
类在\uuuu init\uuuu
方法中分配了一个属性值
,但没有一个属性val
,因此出现错误。混淆可能来自这样一个事实:传递给\uuu init\uu
的变量称为val