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
Initialize
count = 0and a temporary variablecurrentwith the head of the linked liststart.Traverse the list and count nodes.
Stop the loop when temporary variable becomes equal to
None.Return the
count.
class Node:def __init__(self):self.data = 0self.next = Nonedef enter(start_ref, data):new_node = Node()new_node.data = datanew_node.next = start_refreturn new_nodedef nodes_count(start):count = 0current = startwhile current:count = count + 1;current = current.nextreturn countstart = None;start = enter(start, 1);start = enter(start, 11)print("Count of nodes is", nodes_count(start))
Explanation
Line 1: We create a
Nodeclass which represents a node in a linked list.Line 2: This is the
Nodeclass constructor function. When a newNodeobject is created, it calls this function.Lines 3–4: Initialization of
dataandnextvariable to0andNone.Line 7: We define the
enterfunction which takes two parameters and add the node at the start of the linked list.Line 8: By creating the
Nodeclass, a new node is generated andnew_nodenow corresponds to this newly generated node.Line 9: We assign the specified
datavalue to thenew_node.Line 10: The
nextattribute 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_countfor 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 thestartof the linked list.Lines 17–19: The
whileloop 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
countwhen 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
enterfunction.Line 27: We print the total
countof nodes.
Free Resources