Linked List: Perform the below delete operations on a Doubly Linked List

1. Delete a Doubly Linked List node at a given position
2. Delete all occurrences of a given key in a doubly linked list

1. Delete a Doubly Linked List node at a given position

Step 1: Go to the nth position
Step 2: If the node to be deleted is the head node, then change the head pointer to the next node.
Step 3: If the node is not the head node, then delete the node and point the next pointer of the current node to point tot he node after current node.
Step 4: If the node is the last node, then update the previous pointer of the node after the current node before curr.

2. Delete all occurrences of a given key in a doubly linked list

Step 1: If the DLL is empty, then return NULl.
Step 2: Then take a pointer, and check if the node is same as the value, then delete the current node.
#include <iostream>
using namespace std;

class Node 
{
    public:
        int data;
        Node * prev;
        Node * next;
        Node(int d) 
        {
            data = d;
            prev = next = NULL;
        }
};

Node * deleteNodeAtGivenPosition(Node* head, int pos) 
{

    if (head == NULL)
        return head;

    Node * curr = head;

    for (int i = 1; curr != NULL && i < pos; ++i) 
    {
        curr = curr -> next;
    }

    if (curr == NULL)
        return head;

    if (curr -> prev != NULL)
        curr -> prev -> next = curr -> next;

    if (curr -> next != NULL)
        curr -> next -> prev = curr -> prev;

    if (head == curr)
        head = curr -> next;

    delete curr;
    return head;
}


Node * deleteAllOccurOfKey(Node* head, int x)
{
    if (head == NULL)
        return head;

    Node* current = head;
    Node* next;

    while (current != NULL) 
    {

        if (current->data == x) 
        {

            next = current->next;

            {
            	if (head == NULL)
        			return head;

        		if (head == current)
        			head = current->next;

        	    if (current->next != NULL)
        			current->next->prev = current->prev;

        	    if (current->prev != NULL)
        			current->prev->next = current->next;

    			free(current);

            }

            current = next;
        }

        else
            current = current->next;
    }
    return head;    
}



void printList(Node * head) 
{

    Node * curr = head;
    while (curr != nullptr) 
    {
        cout << curr -> data << " ";
        curr = curr -> next;
    }
    cout << endl;
}

int main() {

    Node * head = new Node(1);
    head -> next = new Node(2);
    head -> next -> prev = head;
    head -> next -> next = new Node(3);
    head -> next -> next -> prev = head -> next;

    head = deleteNodeAtGivenPosition(head, 2);

    printList(head);
    
    head = deleteAllOccurOfKey(head, 1);

    printList(head);

    return 0;
}

Output:

1 3
1
Write a Comment

Leave a Comment

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