我试着用Python实现链接列表以实现实际操作,但在这一点上我陷入了困境。我已经能够代码添加和遍历列表,但正面临着从列表中删除elemnt的麻烦。
我正在尝试删除用户在remove ()中传递的元素。
class node (object):
def __init__ (self,data):
self.data = data
self.next = None
class lk (object):
def __init__ (self):
self.current_data = None
self.header = None
def add (self,data):
New_node = node (data)
New_node.next = self.current_data
self.current_data = New_node
self.head = self.current_data
def display (self):
#print 'coming to display', self.current_data
self.current_data = self.head
while (self.current_data is not None):
print self.current_data.data
self.current_data = self.current_data.next
def remove (self,value):
self.value = value
present_node = self.head
self.current_data = self.head
while self.current_data is not None:
if self.head == self.value:
self.head = self.head.next
else:
#k = self.current_data.next
#print k.data
print self.current_data.data
print self.current_data.next
self.current_data = self.current_data.next
k = lk()
k.add (3)
k.add(4)
k.add(5)
k.display()
k.remove(4)
k.display在删除方法中,我试图使用self.current.next.data访问下一个节点的数据,这会导致错误,但我能够访问下一个链接的地址,请有人解释一下我哪里出错了,以及如何纠正它。
发布于 2015-08-11 06:05:52
我在你的代码里找不到几个问题-
self.value = value - in remove()方法,为什么?它为什么在那里?您不需要将要删除的值作为实例变量添加到链接列表中,也不应该。只需在函数中以value的形式完全访问它。self.current_data?您不需要在display()或remove()中更改它,您应该定义一个局部变量,比如current_node`,然后使用它。head更改为指向current_node,这绝不是您想要的。您希望循环,直到您发现下一个数据包含您正在寻找的数据,然后更改当前的下一个指向它的下一个数据。固定密码-
class node (object):
def __init__ (self,data):
self.data = data
self.next = None
class lk (object):
def __init__ (self):
self.current_data = None
self.header = None
def add (self,data):
New_node = node(data)
New_node.next = self.current_data
self.current_data = New_node
self.head = self.current_data
def display (self):
#print 'coming to display', self.current_data
current_node = self.head
while (current_node is not None):
print(current_node.data)
current_node = current_node.next
def remove (self,value):
current_node = self.head
if current_node.data == value:
self.head = current_node.next
return
while current_node.next is not None:
if current_node.next.data == value:
current_node.next = current_node.next.next
break
current_node = current_node.next
k = lk()
k.add (3)
k.add(4)
k.add(5)
k.display()
k.remove(4)
print("Hmm")
k.display()https://stackoverflow.com/questions/31934102
复制相似问题