我想在python中创建一个链接列表类(我毫无意义,但它是一个学习练习),而且我写入的删除节点的方法不起作用如果我尝试删除链接列表的第一个元素。如果要删除的节点是链接列表中的其他任何地方,则该方法工作正常。有人能给我一些见解,看看我哪里出了问题吗?无法删除链接列表中的第一个节点
这里是我的代码迄今:
class Node:
def __init__(self, data=None, next=None):
self.data = data
self.next = next
def __repr__(self):
return repr(self.data)
def printNodes(self):
while self:
print self.data
self = self.next
def removeNode(self, datum):
"""removes node from linked list"""
if self.data == datum:
return self.next
while self.next:
if self.next.data == datum:
self.next = self.next.next
return self
self = self.next
作为一个例子,说我有一个链表1,2,3,4。如果我调用removeNode(1),结果是1,2,3,4。如果我调用removeNode(3),结果是1,2,4。 – carlmonday
您是否将'removeNode'的结果分配回来?换句话说,你做'my_linked_list.removeNode(x)'或'my_linked_list = my_linked_list.removeNode(x)'? –
我做前 – carlmonday