通过单链表的索引值实现删除节点



我需要编写一个函数,删除给定索引值处的节点。索引值作为参数传递。

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

现在,它不删除该索引处的值,而是删除任何具有该值的索引。我如何更改

delete方法中:

(1( 更改:

if self.headval ==index:

至:

if index == 0:

(2( 和变化:

if n.nextval.dataval==index:

至:

index -= 1
if index == 0:

最新更新