Find the Length of a Singly Linked List
Finding the Length of a Singly Linked List
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.
Step-by-Step Process
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:
- Initialize a Counter: Start with a counter set to 0.
- Initialize a Pointer: Start with a pointer set to the head of the list.
- Traverse the List: Move the pointer to the next node, and increment the counter each time, until the pointer reaches the end of the list (i.e., None).
- Return the Counter: The counter now holds the length of the list.
After performing these steps, the length of the linked list will be the value of the counter.
Python Program to Find the Length of a Singly Linked List
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.