【问题标题】:How does this linked list insert implementation work?这个链表插入实现是如何工作的?
【发布时间】:2020-07-13 06:19:36
【问题描述】:
def insert_node(self, node_data):
    node = SinglyLinkedListNode(node_data)

    if not self.head:
      self.head = node
    else :
      self.tail.next = node
    
    self.tail = node

【问题讨论】:

    标签: python-3.x linked-list


    【解决方案1】:
      def insert_node(self, node_data):
        # create a new node with node_data set to value
        node = SinglyLinkedListNode(node_data)
    
        # if the current linked list has no head node, i.e. it is
        # empty, set this new node we're inserting to be the head
        # creating a length 1 linked list with 1 node
        if not self.head:
          self.head = node
        else :
          # if there is a head, then we're going to simply insert
          # our newly created node at the end of the list. since
          # we have a reference to the tail node, we can set the
          # next property on the tail
          self.tail.next = node
        
        # since this method is inserting the new node at the end
        # of the linked list, we now set the tail to reference
        # the newly created node.
        #
        # note this means that the tail and head can be the same
        # in a length 1 list
        self.tail = node
    

    【讨论】:

      猜你喜欢
      • 2020-11-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-04-11
      • 1970-01-01
      相关资源
      最近更新 更多