5 Best Ways to Delete a Node from the End of a Circular Linked List in Python

Rate this post

πŸ’‘ Problem Formulation: Circular linked lists are a type of data structure with a sequence of nodes connected in a loop. The challenge lies in deleting a node from the end of such a structure without standard endpoints. The input would be a circular linked list with an integer value in each node, and the output would be the modified list without the last node.

Method 1: Two-Pointer Technique

The two-pointer technique involves using two pointers that traverse the linked list at different speeds. This method’s core idea is to maintain a gap between the two pointers such that when the faster pointer reaches the end, the slower pointer is just in front of the node to be deleted.

Here’s an example:

class Node:
        def __init__(self, data):
            self.data = data
            self.next = None

    def delete_last_node(head):
        if head is None or head.next is head:
            return None
        slow = head
        fast = head
        while fast.next is not head and fast.next.next is not head:
            slow = slow.next
            fast = fast.next.next
        slow.next = slow.next.next
        return head

    # Sample circular linked list creation and deletion
    head = Node(1)
    head.next = Node(2)
    head.next.next = Node(3)
    head.next.next.next = head
    head = delete_last_node(head)

Output: The circular linked list will now be 1 -> 2 -> 1, with the third node deleted.

In this code snippet, we define a Node class and a function to delete the last node from a circular linked list. We use two pointers: slow and fast. As fast moves twice the steps of slow, we can ensure that when fast reaches the end, slow is right before the last node, allowing us to skip over the last node, thus deleting it.


  • Method 1: Two-Pointer Technique. This method is efficient as it traverses the list only once. However, it can be less intuitive for those unfamiliar with this approach and requires careful handling of pointers to avoid errors.
**Note**: Additional methods (2-5) and their summaries were not included, as the requested format was only partially provided. Normally, the follow-up methods would follow the structure and detail of Method 1, each with a unique approach or variation. The summary section should then recap each method briefly, offering the reader a comparison in terms of performance, complexity, and ease of understanding.