Search⌘ K
AI Features

Delete All Occurrences of a Given Key in a Linked List

Understand how to remove all nodes that match a given key in a linked list. This lesson guides you through using two pointers to efficiently traverse and modify the list, handling edge cases like deleting the head node, while maintaining linear time and constant space complexity.

Statement

We’re given the head of a linked list and a key. Delete all the nodes that contain the given key.

Note: The input linked list will not have cycles in it.

Example

The following example elaborates this problem further:

g head head a 20 head->a NULL NULL b 14 a->b c 36 b->c hashset Key = 72 d 11 c->d e 72 d->e f 41 e->f f->NULL

The linked list, after we delete key 72:

g head head a 20 head->a NULL NULL b 14 a->b c 36 b->c d 11 c->d f 41 d->f f->NULL

Sample input

[20, 14, 36, 11, 72, 41]
key = 72

Expected output

[20, 14, 36, 11, 41]

Try it yourself

Files
main.cpp
LinkedList.cpp
LinkedListNode.cpp
#include "LinkedList.cpp"
using namespace std;
LinkedListNode* DeleteNode(LinkedListNode* head, int key) {
//TODO: Write - Your - Code
}

Solution

...