Finding the length of a singly linked list involves traversing the list and counting the number of nodes. This operation is straightforward and requires iterating through the list until the end is reached.
Consider a singly linked list with the following structure:
Head -> 1 -> 2 -> 3 -> 4 -> None
To find the length of this list, follow these steps:
After performing these steps, the length of the linked list will be the value of the counter.
class Node:
def __init__(self, data):
self.data = data
self.next = None
class SinglyLinkedList:
def __init__(self):
self.head = None
def append(self, data):
new_node = Node(data)
if self.head is None:
self.head = new_node
else:
current = self.head
while current.next:
current = current.next
current.next = new_node
def find_length(self):
count = 0
current = self.head
while current:
count += 1
current = current.next
return count
def traverse(self):
current = self.head
while current:
print(current.data, end=" -> ")
current = current.next
print("None")
# Example usage:
linked_list = SinglyLinkedList()
linked_list.append(1)
linked_list.append(2)
linked_list.append(3)
linked_list.append(4)
print("Linked list:")
linked_list.traverse() # Output: 1 -> 2 -> 3 -> 4 -> None
print("Length of linked list:", linked_list.find_length()) # Output: 4
This Python program defines a singly linked list with methods for appending nodes, finding the length of the list, and traversing the list. The find_length method traverses the list, counts the number of nodes, and returns the length of the list.