How to count the number of nodes in a linked list in Python

A linked list is a linear data structure in which elements, called nodes, are connected through pointers. Each node contains data and a reference (pointer) to the next node in the sequence. The last node’s pointer points to null, indicating the end of the list.

Problem statement

Demonstrate the creation of a singly linked list, the insertion of nodes at the beginning of the list, and the calculation of the total number of nodes in the linked list.

Solution

  1. Initialize count = 0 and a temporary variable current with the head of the linked list start.

  2. Traverse the list and count nodes.

  3. Stop the loop when temporary variable becomes equal to None.

  4. Return the count.

class Node:
def __init__(self):
self.data = 0
self.next = None
def enter(start_ref, data):
new_node = Node()
new_node.data = data
new_node.next = start_ref
return new_node
def nodes_count(start):
count = 0
current = start
while current:
count = count + 1;
current = current.next
return count
start = None;
start = enter(start, 1);
start = enter(start, 11)
print("Count of nodes is", nodes_count(start))

Explanation

  • Line 1: We create a Node class which represents a node in a linked list.

  • Line 2: This is the Node class constructor function. When a new Node object is created, it calls this function.

  • Lines 3–4: Initialization of data and next variable to 0 and None.

  • Line 7: We define the enter function which takes two parameters and add the node at the start of the linked list.

  • Line 8: By creating the Node class, a new node is generated and new_node now corresponds to this newly generated node.

  • Line 9: We assign the specified data value to the new_node.

  • Line 10: The next attribute of the new node (new_node) is set to the current head of the linked list (start_ref).

  • Line 11: We return the new_node.

  • Line 14: We create a new function node_count for counting the number of nodes in linked list.

  • Line 16: We initialize a new variable current. This variable is used to traverse the list and points to the start of the linked list.

  • Lines 17–19: The while loop counts the number of nodes in a linked list by traversing the list, incrementing the count for each node visited, and stopping when the list reaches the end.

  • Line 20: We return the final value of count when the loop completes.

  • Line 23: Intializes an empty linked list.

  • Lines 24–25: We add nodes with different data values to the front of the list using enter function.

  • Line 27: We print the total count of nodes.


Free Resources

Copyright ©2025 Educative, Inc. All rights reserved