0

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 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

2 Comments

Thanks Vincent. In the class LinkedList, where is the next in node = node.next come from? I try to understand it. Also, why does it not define like node.next = node in the class Node? I am trying to understand the reason why both statements are pointing to the next node. But the 1st one is node = node.next and the 2nd one is node.next = node. Thanks
In the Linked List class, you want to move further down the list. So node is just a placeholder. Doing node = node.next in the linked list class is just getting the next node in the list. In the Node class, the node.next = next sets the next value. It might make more sense when understanding how nodes are added to a linked list. Implementation for def addNode(self, data): self.head = Node(data, self.head) As you can see, node.next is set every time we're adding a node.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.