升序添加节点

时间:2018-10-12 16:19:19

标签: python function linked-list

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

上面是我添加函数的代码。我正在尝试添加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语句内,但我不确定如何解决该问题以使其升序。

1 个答案:

答案 0 :(得分:1)

问题出在最后。 因此,让我们看看发生了什么: 数字,动作,结果:

  • 8->如果是第一个-> 8
  • 7->在elif 8中> 7-> 7,8
  • 3,-6->与elif相同-> -6、3、7、8
  • 58->最后---6、3、7、8、58

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

    < / li>

要解决此问题,您需要遍历列表以查看需要放置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