【问题标题】:insert at arbitrary position in doubly linked sentinel list在双向链接的哨兵列表中的任意位置插入
【发布时间】:2017-11-22 08:15:26
【问题描述】:

我知道如何将一个项目附加到一个双向链接的前哨列表中,并且过去已经成功地实现了它。但是,我不确定如何在特定位置插入。例如,我有两个节点,想在它们之间插入一个值。由于链表中没有数字索引(我们使用链表的全部原因......),我如何修复此代码以便它可以在特定位置插入项目(这里的索引是一个描述性术语,不是数字索引):

def insert_element_at(self, val, index):
 new_node = Linked_List.__Node(val) 
 if index >= self.size or index < 0:
      raise IndexError
 elif self.size == 0:
     raise 'To add first value, please use append method.'
 else:
    self.current = self.header.next
    count = 0
    while count != index:
      self.current = self.current.next
      count += 1
    self.current.next = new_node
    new_node.next = self.current.next.next
    new_node.prev = self.current
    self.size += 1

在这种情况下,我使用“计数”来跟踪每次迭代的位置。这似乎不起作用,有人对我如何改进此代码有任何想法吗?我认为我遇到的主要问题是当它遇到我的字符串方法时:

def __str__(self):  
  if self.size == 0:
    return '[ ]'
  self.current = self.header.next
  s = '[ '
  while self.current is not self.trailer:
    s += str(self.current.val)
    s += ', '
    self.current = self.current.next
  s += ' ]'
  return s

任何关于我如何改进它的想法或帮助都会很棒!

【问题讨论】:

    标签: python-3.x doubly-linked-list


    【解决方案1】:

    我认为问题在于将新节点链接到现有节点的操作顺序。当您将self.current.next = new_node 作为第一步时,您将无法访问self.current.next 的原始值(应该成为新值之后的节点)。

    我会这样做:

    while count != index:
      self.current = self.current.next
      count += 1
    new_node.prev = self.current
    new_node.next = self.current.next
    self.current.next.prev = new_node
    self.current.next = new_node
    

    虽然我没有在上面这样做,但我还建议您将 current 设为局部变量而不是 self 的属性,因为函数中的局部变量比全局变量或属性更快地访问。

    【讨论】:

    • 谢谢!我不敢相信我在把所有东西都扔掉的顺序中犯了这样一个简单的错误!并感谢您关于将其设为局部变量的建议;我正在学习更多关于我当前课程的表现的信息,这也是我试图在我的所有课程中改进的内容。
    • 它现在正在插入,但它在我要求它插入之后的一个索引处插入。知道为什么会这样吗?
    • 我猜这就是你开始self.current的方式。尝试使用self.current = self.header(而不是self.header.next)。
    • 是的,就是这样!这些当前的指针将是我(和我的程序)的死亡。不过我现在明白了很多!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-01-22
    • 1970-01-01
    • 2015-05-21
    • 2021-10-11
    • 1970-01-01
    • 1970-01-01
    • 2011-12-12
    相关资源
    最近更新 更多