【问题标题】:Implementing a delete node by index value for singly linked list为单链表实现按索引值删除节点
【发布时间】: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。将indexi 进行比较,而不是将其与dataval 进行比较。

标签: python python-3.x data-structures linked-list singly-linked-list


【解决方案1】:

delete 方法中:

(1)变化:

if self.headval ==index:

到:

if index == 0:

(2) 并改变:

if n.nextval.dataval==index:

...到:

index -= 1
if index == 0:

【讨论】:

    猜你喜欢
    • 2010-12-23
    • 2020-08-11
    • 2020-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多