Length of a Linked List in Python



To calculate the length of a Linked list, we traverse the list, counting each node until we reach the end, where the next node is None. Suppose, we have a singly linked list, we have to find its length. The linked list has fields next and val. So, if the input is like [2 -> 4 -> 5 -> 7 -> 8 -> 9 -> 3], then the output will be 7. The two commonly used methods to find the length of a linked list are as follows -

  • Iterative Approach: In involves traversal of the Linked List with an additional variable to count the number of nodes in the Linked List.

  • Recursive Approach: Takes a node as an argument and calls itself with the next node until we reach the end of the Linked List.

Using Iterative Approach

Some of the steps involved in finding the length of a linked list using an iterative approach.

  • Initialize a counter

  • Traverse the linked list

  • Return the count

Initialize a counter

Starting by setting a counter count to 0. This variable will keep track of how many nodes we have encountered in the linked list.

# Initialize the counter to zero
class Solution:
    def solve(self, node):
        count = 0

Traverse the linked list.

Using a while loop, we traverse the linked list from the head node to every other node. Advancing the counter by 1 for every node before following the subsequent reference to reach the next node.

# Traverse until the node is not None
while node:  
    count += 1  
    node = node.next  

Return the count

The loop stopped when the node became None, which indicates the end of the linked list. Finally, return the counter value, to get the length of the Linked list.

return count

Example

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

def make_list(elements):
    head = ListNode(elements[0])
    ptr = head
    for element in elements[1:]:
        new_node = ListNode(element)
        ptr.next = new_node
        ptr = ptr.next
    return head

class Solution:
    def solve(self, node):
        count = 0
        while node:
            count += 1
            node = node.next
        return count

ob = Solution()
head = make_list([2, 4, 5, 7, 8, 9, 3])
print(ob.solve(head))  

Output

7

Using Recursive Approach

Some of the steps involved in finding the length of a linked list using a recursive approach

  • Linked List Node definition

  • Base Case

  • Recursive Case

  • Return the Total Count

Defining a linked list node

Consider a class Node defines a linked list node with a data value data and a reference next to the next node n the list.

# Linked List Node definition
class Node:
    def __init__(self, new_data):
        self.data = new_data  
        self.next = None  

Base Case

When the recursion reaches a node with head == None, it stops and returns 0. This represents the end of the list.

if head is None:
    return 0 

Recursive Case

Otherwise, we count the current node as 1 and recursively call the function on the next node (head.next), collecting the total count until it reaches the base case.

return 1 + count_nodes(head.next) 

Return the Total Count

Once we reach the base case, each recursive call returns the total number of nodes in the linked list.

# Driver code to test the function
if __name__ == "__main__":
    head = Node(2)
    head.next = Node(4)
    head.next.next = Node(5)
    head.next.next.next = Node(7)
    head.next.next.next.next = Node(8)
	head.next.next.next.next.next = Node(9)
	head.next.next.next.next.next.next = Node(3)
	
    # Function call to count the number of nodes
    print("Count of nodes is", count_nodes(head))

Example

# Linked List Node
class Node:
    def __init__(self, new_data):
        self.data = new_data
        self.next = None

# Recursively count number of nodes in linked list
def count_nodes(head):
    # Base Case
    if head is None:
        return 0

    # Count this node plus the rest of the list
    return 1 + count_nodes(head.next)


# Driver code
if __name__ == "__main__":
    head = Node(1)
    head.next = Node(3)
    head.next.next = Node(1)
    head.next.next.next = Node(2)
    head.next.next.next.next = Node(1)

    # Function call to count the number of nodes
    print("Count of nodes is", count_nodes(head))

Output

Count of nodes is 5
Updated on: 2024-10-09T14:27:37+05:30

7K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements