Find length of linked list (Iterative) in Python

Here in this tutorial, we will learn how to find the length of a linked list iteratively.

So out of the two methods, we have already learned about the recursive approach and in the tutorial, we will take a look at the iterative approach.

Find the length of the linked list iteratively

Unlike the recursive approach, we need a count pointer in the iterative approach which will store the length of the linked list.

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

def takingInput():
    head = tail = None
    list1 = [int(i) for i in input().split()]
    
    for i in list1:
        if i == -1:
            break
        
        NewNode = Node(i)
        
        if head == None:
            head = NewNode
            tail = NewNode
        else:
            tail.next = NewNode
            tail = NewNode
    
    return head


def LengthofLL(head):
    count = 0
    while head:
        count += 1
        head = head.next
        
    return count

Head = takingInput()
length = LengthofLL(Head)
print('the length of the linked list is : ',length)

Output:

1 2 3 4 5 6 7 -1
the length of the linked list is : 7

In the code written above, we have firstly created a node class that will help us in creating nodes.

Then we created a function that will take input from the user to make a linked list.

Now coming to the length function we have taken a count variable which will store the length of the linked list and increase the count variable by ‘1’ each time till the head is not pointing to ‘None’. And in the end, return the count.

Hence we have seen how to get the length of the linked list iteratively.

To see the recursive approach visit:

Leave a Reply

Your email address will not be published. Required fields are marked *