【问题标题】:How do I update my self.tail in a method for deleting a node at a specific position when the position is the last node?当位置是最后一个节点时,如何在删除特定位置的节点的方法中更新我的 self.tail?
【发布时间】:2018-01-19 10:17:15
【问题描述】:

方法从谷歌上得到并稍作改动:

def removeNodeAtPosition(self, position):
    if self.head == None:
        print("List is empty")
        return
    current = self.head

    if position == 0:               
        self.head = current.next
        current = None
        self.size-=1
        return

    for i in range(position-1):            
        current = current.next
        if current == None:
            break
    if current == None:
        return
    if current.next == None:
        return
    next = current.next.next
    current.next = None
    current.next = next
    if position == self.size:   #two lines here used for updating self.tail
        self.tail = current
    self.size-=1

标题主要是这样说的:当我用这种方法删除节点的尾部时,我的 self.tail 值没有改变。我不知道我的两行代码的位置是否出错,或者代码是否错误。我已经完好无损地保留了最近的尝试。任何解决此问题的帮助将不胜感激。

【问题讨论】:

    标签: python data-structures linked-list nodes singly-linked-list


    【解决方案1】:

    考虑删除current.next 而不是删除current。这样,如果current.next 是最后一个元素,那么current 将是新的tail

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-10-24
      • 2010-10-30
      • 1970-01-01
      • 2016-08-12
      • 1970-01-01
      • 1970-01-01
      • 2016-08-23
      • 1970-01-01
      相关资源
      最近更新 更多