插入双向链接标记列表中的任意位置

时间:2017-06-20 00:40:06

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

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

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

我使用'count'作为在每种迭代中跟踪这种情况下的位置的方法。这似乎不起作用,有没有人有任何关于如何改进此代码的想法?我认为我遇到的主要问题是它何时遇到我的字符串方法:

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

关于如何改进这一点的任何想法或帮助都会很棒!

1 个答案:

答案 0 :(得分:0)

我认为问题在于将新节点链接到现有节点的操作顺序。当您执行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的属性,因为函数中的局部变量比全局变量更快。或属性。

相关问题