Delete the Head Node of a Singly Linked List


Deleting the Head Node

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.


Step-by-Step Process

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:

  1. Check if the List is Empty: If the head is None, the list is already empty, and there is nothing to delete.
  2. Update the Head Reference: Update the head reference to point to the next node in the list (node with value 2).
  3. Dispose of the Old Head Node: Optionally, set the next reference of the old head node to None to help the garbage collector (if applicable).

After performing these steps, the linked list will have the following structure:


Head -> 2 -> 3 -> 4 -> None

Python Program to Delete the Head Node

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.