Traversing a singly linked list involves visiting each node in the list in sequence to perform actions or retrieve data. This operation is fundamental for various linked list manipulations, including searching, updating, and displaying elements.
Consider a singly linked list with the following structure:
Head -> 1 -> 2 -> 3 -> 4 -> None
To traverse this list, follow these steps:
Let's apply these steps to the example 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 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("Traversal of the linked list:")
linked_list.traverse() # Output: 1 -> 2 -> 3 -> 4 -> None
This Python program defines a singly linked list with methods for appending nodes and traversing the list. The traverse method visits each node and prints its value in sequence.