Skip to main content

Deleting All Occurrences of a Key in a Doubly Linked List

KANISHKA GUPTA
EditReport

Deleting All Occurrences of a Key in a Doubly Linked List (DLL)

Introduction​

A Doubly Linked List (DLL) is a data structure consisting of nodes, where each node contains three components:

  • A data field
  • A pointer to the next node
  • A pointer to the previous node.

This structure allows traversal in both directions and efficient insertion and deletion operations.

Video Explanation​

Problem Statement​

Given a DLL and a key, the task is to delete all nodes that contain the specified key.

Example​

Input:

DLL: 10 <-> 20 <-> 30 <-> 20 <-> 40 Key: 20

Output:

DLL: 10 <-> 30 <-> 40

Approach​

  1. Initialize Pointers: Start with a pointer at the head of the list.
  2. Traverse the DLL: Loop through the list and check each node's data against the key.
  3. Delete Nodes:
    • If a node's data matches the key:
      • Adjust the pointers of the previous and next nodes.
      • If the node is the head, update the head pointer.
      • Move to the next node after deletion.
  4. Continue Traversal: Keep traversing until the end of the list.

Implementation​

Solutions​

#include <iostream>

class Node {
public:
int data;
Node* next;
Node* prev;

Node(int data) {
this->data = data;
this->next = nullptr;
this->prev = nullptr;
}
};

class DoublyLinkedList {
public:
Node* head;

DoublyLinkedList() {
head = nullptr;
}

// Method to append a node at the end of the list
void append(int data) {
Node* newNode = new Node(data);
if (head == nullptr) {
head = newNode;
return;
}
Node* last = head;
while (last->next != nullptr) {
last = last->next;
}
last->next = newNode;
newNode->prev = last;
}

// Method to delete all occurrences of a key
void deleteAllOccurrences(int key) {
Node* current = head;

while (current != nullptr) {
if (current->data == key) {
// Node to be deleted
if (current->prev != nullptr) {
current->prev->next = current->next;
}
if (current->next != nullptr) {
current->next->prev = current->prev;
}
if (current == head) { // Move hea
Track Your Progress

Done with this topic? Mark it as complete to track your progress.

đŸ’Ŧ Discuss this page

Have a question or spot something confusing in "Deleting All Occurrences of a Key in a Doubly Linked List"? Ask below — it's backed by GitHub Discussions, so maintainers get notified like any other GitHub activity.