问题描述
我需要编写一个函数来删除给定索引值处的节点。索引值作为参数传递。
删除:此方法从链接列表中删除一个节点。如果将索引作为参数传递,则该方法应删除该索引处的节点。如果没有传递索引,则删除列表中的第一项
到目前为止,我有:
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
现在,与其删除该索引上的值,不如删除具有该值的任何索引。我该如何更改
解决方法
在delete
方法中:
(1)更改:
if self.headval ==index:
收件人:
if index == 0:
(2)并更改:
if n.nextval.dataval==index:
...至:
index -= 1
if index == 0: