我想知道为什么以下不起作用。
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
def remove(self, value):
if self is None:
return False
if self.data == value:
if self.next:
self.data = self.next.data
self.next = self.next.next
else:
del self
else:
self.next.remove(value)
node = Node(4)
node.append(Node(3))
node.remove(3)
print node.next.data
#prints 3
del
不会从链表中删除元素。我必须修改delete()
函数,以便我有一个指向目标元素父级的指针。
class Node(object):
def __init__(self, data, next=None):
self.data = data
self.next = next
def remove(self, value):
if self is None:
return False
if self.data == value:
if self.next:
self.data = self.next.data
self.next = self.next.next
else:
del self
else:
current = self
while current.next:
if current.next.data == value:
if current.next.next:
current.next = current.next.next
else:
current.next = None
从控制台,
node = Node(4)
current = node
del current #node is not deleted because I am only deleting the pointer
del node #node is deleted
这在我看来是合乎逻辑的。但是,我不确定为什么第一个代码块不能按我的预期工作。