【问题标题】:Add a node in ascending order按升序添加节点
【发布时间】:2018-10-12 16:19:18
【问题描述】:
def add(self, value):
    #write your code here

    if self.head == None:
        new_node = Node(value)
        self.head = new_node
        self.tail = self.head


    elif self.head.value > new_node.value:
        new_node = Node(value)
        new_node.value = value
        new_node.next = self.head
        self.head = new_node

    else:
        new_node = Node(value)
        self.tail.setNext(new_node)
        self.tail = new_node

    self.count += 1

上面是我的函数add的代码。我正在尝试添加 Node 对象 以升序排列到一个链表中,这样当我打印它时,它会显示为:

>>> x.add(8)
>>> x.add(7)
>>> x.add(3)
>>> x.add(-6)
>>> x.add(58)
>>> x.add(33)
>>> x.add(1)
>>> x.add(-88)
>>> print(x)
Head:Node(-88) Tail:Node(58)
List:-88 -6 1 3 7 8 33 58

但是当我使用上面的代码执行此操作时,它会打印为:

>>> print(x)
Head:Node(-88)
Tail:Node(1)
List:-88 -6 3 7 8 58 33 1

我 80% 确定问题出在 elif 语句中,但我不确定如何解决它以使其按升序运行。

【问题讨论】:

  • 当您到达elif ...: 时,new_node 尚未创建。如果您在这里没有收到错误,可能是因为您有一个同名的全局代码,或者您在此处显示的代码不是真实的。只需与 value 比较即可。

标签: python function linked-list


【解决方案1】:

问题出在最后一个else上。 那么让我们看看发生了什么: 数量、动作、结果:

  • 8 -> 在第一个 if -> 8
  • 7 -> 在 elif 8 > 7 -> 7,8
  • 3,-6 -> 与 elif 相同 -> -6, 3, 7, 8
  • 58 -> 最后一个 -> -6, 3, 7, 8, 58

    当 33 出现并再次进入最后一个 else 时出现错误,因为它大于 -6 的 head,结果变为 -6、3、7、8、58、33。

要解决此问题,您需要遍历列表以查看需要放置 33 的位置,您不能仅通过将项目放在开头或结尾来获得排序列表。

def add(self, value):
    #write your code here

    #if list is empty
    if self.head == None:
        new_node = Node(value)
        self.head = new_node
        self.tail = self.head

    #elif value < head set new head
    elif self.head.value > value:
        new_node = Node(value)
        new_node.value = value
        new_node.next = self.head
        self.head = new_node


    #elif value > tail set new tail
    elif value > self.tail.value:
      new_node = Node(value)
      self.tail.setNext(new_node)
      self.tail = new_node
    # and finally you need to loop to find the sweet spot
    else:
      # we will start the search from the head
      current_node = self.head
      # while the value we wish to insert is bigger than the next one
      while value > current_node.next.value:
        # set the current one to the next one
        current_node = current_node.next
      # finally we reached a node which is smaller than the value we wish to insert
      # but its next node is bigger
      new_node = Node(value)
      # set the new nodes next to the bigger node
      new_node.next = current_node.next
      # and the curren't node's next to the new one
      current_node.next = new_node

【讨论】:

  • 我在我的代码中实现了代码,它仍然产生与上面相同的输出。
  • @BobBills 你的 while 循环有点危险,因为它可能会一直走到 curr_node.nextNone 的末尾
  • 是的,我的错,我把价值的 elif > self.head 而不是价值 > self.tail.
  • @slider 是的,这很危险,因为我把之前的 elif 搞砸了。现在它正在正确检查值是否为
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-01-27
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多