Deleting the head node of a singly linked list involves updating the head reference to point to the next node in the list. This operation is straightforward and efficient, as it only requires updating one pointer.
Consider a singly linked list with the following structure before deletion:
Head -> 1 -> 2 -> 3 -> 4 -> None
We want to delete the head node (node with value 1). Follow these steps:
After performing these steps, the linked list will have the following structure:
Head -> 2 -> 3 -> 4 -> None
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 delete_head(self):
if self.head is None:
print("The list is already empty.")
return
self.head = self.head.next
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 before deleting head:")
linked_list.traverse() # Output: 1 -> 2 -> 3 -> 4 -> None
linked_list.delete_head()
print("Linked list after deleting head:")
linked_list.traverse() # Output: 2 -> 3 -> 4 -> None
This Python program defines a singly linked list with methods for appending nodes, deleting the head node, and traversing the list. The delete_head method updates the head reference to point to the next node in the list, effectively removing the current head node.