Delete the Last Node of a Singly Linked List



Deleting the Tail Node

Deleting the tail node of a singly linked list involves traversing the list to find the second-to-last node and updating its next reference to None. This operation requires traversing the list to find the tail and the node before it.


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 tail node (node with value 4). 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. Check if the List has Only One Node: If the head's next reference is None, set the head to None, making the list empty.
  3. Traverse to the Second-to-Last Node: Start at the head and follow the next references until you reach the node before the last node (node with value 3).
  4. Update the Second-to-Last Node's Next Reference: Set the next reference of the second-to-last node to None, removing the last node from the list.

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


Head -> 1 -> 2 -> 3 -> None

Python Program to Delete the Tail 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_tail(self):
        if self.head is None:
            print("The list is already empty.")
            return
        if self.head.next is None:
            self.head = None
            return
        current = self.head
        while current.next.next:
            current = current.next
        current.next = None

    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 tail:")
linked_list.traverse()  # Output: 1 -> 2 -> 3 -> 4 -> None
linked_list.delete_tail()
print("Linked list after deleting tail:")
linked_list.traverse()  # Output: 1 -> 2 -> 3 -> None

This Python program defines a singly linked list with methods for appending nodes, deleting the tail node, and traversing the list. The delete_tail method checks if the list is empty or has only one node, traverses to the second-to-last node, and updates its next reference to remove the last node from the list.