Traversal of Singly Linked List in Python
To traverse a singly linked list in Python, you simply need to iterate through each node starting from the head node and print the data of each node until you reach the end of the list (i.e. when the next pointer of a node is None).
Below is the implementation of the above idea:
# Python Program for traversal of Singly Linked list
class Node:
def __init__(self, data):
self.data = data
self.next = None
def insert_at_beginning(head, data):
new_node = Node(data)
new_node.next = head
return new_node
def traverse(head):
current = head
while current:
# Print the current node's data followed by an arrow and space
print(str(current.data) + " -> ", end=" ")
current = current.next
# At the end of the list, print None to indicate no further nodes
print("None")
# Singly linked list created and its head stored in a variable named "head"
head = None
head = insert_at_beginning(head, 4)
head = insert_at_beginning(head, 3)
head = insert_at_beginning(head, 2)
head = insert_at_beginning(head, 1)
# To traverse and print the nodes:
traverse(head)
Output
1 -> 2 -> 3 -> 4 -> None
Singly Linked List in Python
A Singly Linked List is a type of data structure that is made up of nodes that are created using self-referential structures. Each node contains a data element and a reference (link) to the next node in the sequence. This allows for a dynamic and efficient management of data elements.
Table of Content
- What is a Singly Linked List?
- Representation of Singly linked list in Python
- Traversal of Singly Linked List in Python
- Insertion of Singly Linked List in Python
- Deletion of Singly Linked List in Python
- Related Practice Problem on Singly Linked List