Python Program For Finding Length Of A Linked List
Last Updated :
22 Apr, 2023
Write a function to count the number of nodes in a given singly linked list.
For example, the function should return 5 for linked list 1->3->1->2->1.
Iterative Solution:
1) Initialize count as 0
2) Initialize a node pointer, current = head.
3) Do following while current is not NULL
a) current = current -> next
b) count++;
4) Return count
Following is the Iterative implementation of the above algorithm to find the count of nodes in a given singly linked list.
Python
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
self .head = new_node
def getCount( self ):
temp = self .head
count = 0
while (temp):
count + = 1
temp = temp. next
return count
if __name__ = = '__main__' :
llist = LinkedList()
llist.push( 1 )
llist.push( 3 )
llist.push( 1 )
llist.push( 2 )
llist.push( 1 )
print ( "Count of nodes is :" ,
llist.getCount())
|
Output
('Count of nodes is :', 5)
Time Complexity: O(n), where n represents the length of the given linked list.
Auxiliary Space: O(1), no extra space is required, so it is a constant.
Recursive Solution:
int getCount(head)
1) If head is NULL, return 0.
2) Else return 1 + getCount(head->next)
Following is the Recursive implementation of the above algorithm to find the count of nodes in a given singly linked list.
Python
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def push( self , new_data):
new_node = Node(new_data)
new_node. next = self .head
self .head = new_node
def getCountRec( self , node):
if ( not node):
return 0
else :
return 1 + self .getCountRec(node. next )
def getCount( self ):
return self .getCountRec( self .head)
if __name__ = = '__main__' :
llist = LinkedList()
llist.push( 1 )
llist.push( 3 )
llist.push( 1 )
llist.push( 2 )
llist.push( 1 )
print ( "Count of nodes is :" ,
llist.getCount())
|
Output
('Count of nodes is :', 5)
Time Complexity: O(n), where n represents the length of the given linked list.
Auxiliary Space: O(n), for recursive stack where n represents the length of the given linked list.
Approach: Linear Traversal Method
- Define a Node class with two attributes: data to store the value of the node, and next to store a reference to the next node in the list.
- Define a LinkedList class with a single attribute: head to store a reference to the first node in the list.
- Define an append method in the LinkedList class to add a new node to the end of the list.
- Define a length method in the LinkedList class to find the length of the list.
- Initialize a count variable to 0 and a current_node variable to the head of the list.
- Enter a while loop that continues until current_node is None.
- Increment the count variable by 1 on each iteration of the loop.
- Update current_node to be the next node in the list on each iteration of the loop.
- Return the value of the count variable as the length of the list.
Python3
class Node:
def __init__( self , data):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def append( self , data):
new_node = Node(data)
if self .head is None :
self .head = new_node
return
current_node = self .head
while current_node. next :
current_node = current_node. next
current_node. next = new_node
def length( self ):
count = 0
current_node = self .head
while current_node:
count + = 1
current_node = current_node. next
return count
linked_list = LinkedList()
linked_list.append( 1 )
linked_list.append( 2 )
linked_list.append( 3 )
linked_list.append( 4 )
linked_list.append( 5 )
print (linked_list.length())
|
The time complexity of the approach used in the program is O(n),
The auxiliary space used by the program is O(1).
Approach Name: Hash Table Method
Steps:
- Define a linked list class with a head pointer that points to the first node of the linked list.
- Create an empty hash table to store visited nodes.
- Traverse the linked list using the head pointer.
- For each node, check if it is already present in the hash table. If it is, stop traversing.
- If the node is not in the hash table, add it to the hash table and move to the next node.
- Return the size of the hash table as the length of the linked list.
Python3
class Node:
def __init__( self , data = None ):
self .data = data
self . next = None
class LinkedList:
def __init__( self ):
self .head = None
def insert( self , data):
new_node = Node(data)
if self .head is None :
self .head = new_node
else :
current_node = self .head
while current_node. next :
current_node = current_node. next
current_node. next = new_node
def length( self ):
visited_nodes = {}
current_node = self .head
while current_node:
if current_node in visited_nodes:
break
visited_nodes[current_node] = True
current_node = current_node. next
return len (visited_nodes)
linked_list = LinkedList()
linked_list.insert( 1 )
linked_list.insert( 2 )
linked_list.insert( 3 )
print (linked_list.length())
|
Time Complexity: O(n), where n is the length of the linked list, due to the traversal of the linked list.
Auxiliary Space: O(n), due to the hash table used to store visited nodes.
Please refer complete article on Find Length of a Linked List (Iterative and Recursive) for more details!
Like Article
Suggest improvement
Share your thoughts in the comments
Please Login to comment...