【发布时间】:2020-10-30 16:45:11
【问题描述】:
我需要编写一个函数,删除给定索引值处的节点。索引值作为参数传递。
Delete:此方法从链表中删除一个节点。如果索引作为参数传递,则该方法应删除该索引处的节点。如果没有传递索引,则删除列表中的第一项
到目前为止,我有:
class Node:
def __init__(self, dataval=None):
self.dataval = dataval
self.nextval = None
class LinkedList:
def __init__(self):
self.headval = None
def __str__(self):
node = self.headval
output = "[ "
while(node != None):
output = output + str(node.dataval) + ", "
node = node.nextval
if(len(output) > 2):
output = output[:-2]
return output + " ]"
def delete(self, index=0):
if self.headval is None:
print("This list has no element to delete")
return
if self.headval ==index:
self.headval=self.headval.nextval
return
n=self.headval
while n.nextval is not None:
if n.nextval.dataval==index:
break
n=n.nextval
if n.nextval is None:
print("Item not found in list")
else:
n.nextval=n.nextval.nextval
现在不是删除该索引处的值,而是删除具有该值的任何索引。我该如何更改它
【问题讨论】:
-
当您编写
if n.nextval.dataval==index:时,您将搜索的index与节点的值进行比较。相反,您应该与节点的索引进行比较!初始化索引计数器i = 0,然后在while 循环的每次迭代中将i递增1。将index与i进行比较,而不是将其与dataval进行比较。
标签: python python-3.x data-structures linked-list singly-linked-list