Deletion At Different Positions in A Circular Linked List

Introduction

The linked list is one of the most important concepts to know while preparing for interviews. Having a good grasp of a linked list can be a huge plus point in coding interviews.

Problem Statement

We will be given a circular linked list and a position, and we need to delete the element present at that position in the list.

Note: we need to follow 0 based indexing while deleting the nodes

Problem Statement Understanding

Let's try to understand the problem with the help of an example.

If the linked list given to us is:

Now, if position = 0.

  • Then, we need to delete the first node of the list, and after deletion, the list will now look like this:

If the position = 2.

  • Then, we need to delete the third node, and the list after deletion will look like this:

At this point, we have understood the problem statement. Now we will try to formulate an approach for this problem.

Before moving to the approach section, try to think about how you can approach this problem.

  • If stuck, no problem, we will thoroughly see how we can approach this problem in the next section.

Let’s move to the approach section.

Approach

We will divide our problem into three sections:
1) When position = 0:
a) It means that we need to delete the first node of the circular linked list.
b) In this case, we need to reach the last node and then connect it with the second node.
c) After that, we will update the head pointer for the list.

2) When position = length of the list (we need to delete the last node):
a) In this case, we need to reach the last second node and connect it with the first node.

3) When we need to delete a middle node:
a) We need to keep track of node position while iterating the list.
b) when we find the node at the specified position, we need to connect its previous node with its next node.

Let's move to the algorithm section to see the above approach in more depth.

Algorithm

1) First, calculate the length of the list and save it in len variable.
2) Initialize a variable count by 1.
3) If the head is NULL, then it means that the list is empty, so return from the function.
4) If the position is less than 0 or greater than len, then return from the function.
5) If position == 0 then, call deleteFirstNode function:

  • Initialize curr and left with the head of the list.
  • Return from the function if the head is NULL.
  • Make the head NULL and return from the function, if left->next is left (this is the case when there is only 1 node in the list).
  • Run a while loop till left->next is not equal to head.
    • Inside the loop, advance left by one node and update curr with the next node of left.
  • Now, when the loop is executed completely, connect the next pointer of left to the next node of curr.
  • Update the head node by left->next.
  • Delete the old head node, i.e., curr.
    6) If position == (len-1) then, call deleteLastNode function:
  • Initialize the curr pointer with head and left with NULL.
  • Return from the function if the head is NULL.
  • Make the head NULL and return from the function, if curr->next is curr (this is the case when there is only 1 node in the list).
  • Run a while loop till curr->next is not equal to head.
    • Inside the loop, save the value of curr in left and advance curr by one node.
  • Now, when the loop is executed completely, connect the next pointer of left to the next node of curr.
  • Update the head node by left->next.
  • Delete the old head node, i.e., curr.
    7) Run a while loop till len is positive.
  • If position is equal to count then,
    • Connect previous node’s next pointer to current node’s next pointer.
    • Delete the curr pointer and return from the function.
  • Advance previous by one node and update curr to the node next to previous.
  • Decrement len and increment count by one.
    8) Return from the function once while loop breaks.

Dry Run

Code Implementation

#include 
using namespace std;

class Node {
    public:
    int data;
    Node* next;
    Node(int d)
    {
        data = d;
        next = NULL;
    }
};
// This function will print data of 
// all the nodes present in the list
void Display(Node* head)
{
    Node* temp = head;
 
    // In case of an empty list:
    if (head == NULL) {
        printf("\nDisplay List is empty\n");
        return;
    }
 
    // iterate the complete list
    else {
        do {
            cout<<(temp->data);
            temp = temp->next;
            cout<<" ";
        } while (temp != head);
    }
    cout<<'\n';
}

// This function calculates the 
// number of nodes in the list
int Length(Node* head)
{
    Node* temp = head;
    int len = 0;
 
    // in case of an empty list, return 0
    if (head == NULL) {
        return 0;
    }
 
    // iterate the complete list
    else {
        do {
            temp = temp->next;
            len++;
        } while (temp != head);
    }
    return len;
}

// This node deletes the first node
// of the list
void deleteFirstNode(Node** head)
{
    Node *left = *head, *curr = *head;
 
    // if the list is empty
    if (*head == NULL) {
        printf("\nList is empty\n");
        return;
    }
 
    // In case, the list has a single node 
    if (left->next == left) {
        *head = NULL;
        return;
    }
 
    // iterate the complete list
    while (left->next != *head) {
 
        left = left->next;
        curr = left->next;
    }
 
    // left will be pointing to the last node 
    // and curr will be the head of the list
    // so, we will connect left with the curr->next
    left->next = curr->next;
 
    // make second node as head node
    *head = left->next;
    free(curr);
 
    return;
}

// This function deletes the last
// node of the list
void deleteLastNode(Node** head)
{
    Node *curr = *head,  *left = NULL;
 
    // if the list is empty
    if (*head == NULL) {
        printf("\nList is empty\n");
        return;
    }
 
    // In case, the list has a single node 
    if (curr->next == curr) {
        *head = NULL;
        return;
    }
 
    //iterate the list 
    while (curr->next != *head) {
        left = curr;
        curr = curr->next;
    }
 
    left->next = curr->next;
    *head = left->next;
    free(curr);
 
    return;
}

void deleteAtPosition(Node** head, int position)
{
    // find length of the list
    int len = Length(*head);
    int count = 1;
    Node *previous = *head, *curr = *head;
 
    // check if the list is empty
    if (*head == NULL) {
        printf("\nDelete Last List is empty\n");
        return;
    }
 
    // check if the given position is out of
    // bound of the list
    if (position >= len || position < 0) {
        printf("\nposition is not Found\n");
        return;
    }
 
    // first node deletion
    if (position == 0) {
        deleteFirstNode(head);
        return;
    }
    // last node deletion
    else if(position == len-1){
        deleteLastNode(head);
        return;
    }
 
    // iterate the complete list
    while (len > 0) {
 
        // delete the node when position is found
        if (position == count) {
            previous->next = curr->next;
            free(curr);
            return;
        }
        previous = previous->next;
        curr = previous->next;
        len--;
        count++;
    }
    return;
}

int main()
{
    Node *head = new Node(3);
    head->next = new Node(7);
    head->next->next = new Node(2);
    head->next->next->next = new Node(5);
    head->next->next->next->next = head;
    cout<<"Original list ";
    Display(head);
    cout<<"After deleting third node ";
    deleteAtPosition(&head,2);
    Display(head);
    cout<<"After deleting last node ";
    deleteAtPosition(&head,Length(head)-1);
    Display(head);
    cout<<"After deleting first node ";
    deleteAtPosition(&head,0);
    Display(head);
}

Output

Original list 3 7 2 5
After deleting third node 3 7 5
After deleting last node 3 7
After deleting first node 7

Time Complexity: O(n), where n is the number of nodes in the list

So, in this blog, we have tried to explain how you can delete nodes at different positions in a circular list in the most optimal way. If you want to practice more questions on linked lists, feel free to solve them at Prepbytes (Linked Lists).

Previous post Detect and Remove the loop in a linked list
Next post Quick Overview Of What A Microsoft Hiring Process Looks Like!

Leave a Reply

Your email address will not be published. Required fields are marked *