Как работает эта реализация вставки связанного списка? - PullRequest
0 голосов
/ 13 июля 2020
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

1 Ответ

0 голосов
/ 13 июля 2020
  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
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...