0
votes

I am practicing Python, Linked List:

class LinkedList

class LinkedList:
def init(self): self.head = None

def __repr__(self):
    node = self.head
    nodes = []
    while node is not None:
        nodes.append(node.data)
        node = node.next
    nodes.append('None')
    print(nodes)
    return ' -> '.join(nodes)

Question:

  • We all know that to point the 1st node to the 2nd node: first_node.next = second_node
  • However, in the class LinkedList above, we can see: node = node.next

1/ What is the difference between them?

2/ In the class LinkedList, where is the next method from?

Thanks for your advance.

1

1 Answers

1
votes

node = node.next could better be described as current_node = node.next since it is not always the first node. In the __repr__ function, you're basically setting a node to the head. Then printing the data in that node (which is head). Then we set node to node.next which makes node set to the second node. If there were a third, fourth, ... node in the list, then node would eventually get set to them until the last node.

The code you sent is incomplete because it needs to also implement the node class along with the linked list class. This basically holds the data and a pointer to the next node.

class Node:
  def __init__(self, data, next = None):
    self.data = data
    self.next = next

So next would not be a method but rather a member which holds the address to the next node.