find the length of a linked list in python

To find the length of a singly linked list in python, we need to traverse the entire linked list and count the number of nodes present.

Here's an implementation:

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

class LinkedList:
    def __init__(self):
        self.head = None

    def append(self, data):
        new_node = Node(data)

        if not self.head:
            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
645 chars
31 lines

In the LinkedList class, we have a method length() which traverses the linked list by starting from the head node and incrementing a counter until the last node is reached. This counter is returned as the length of the linked list.

We can create a new instance of the LinkedList class, append some values to it and then call the length() method as follows:

main.py
linked_list = LinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.append(4)

print(linked_list.length())  # Output: 4
157 chars
8 lines

gistlibby LogSnag