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.py645 chars31 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.py157 chars8 lines
gistlibby LogSnag