Challenge: Remove a Value Everywhere
Completed
Build a linked list, then remove every node with the target value (including at the head), freeing each removed node with delete. Print what's left, or empty.
Input
Line 1: n. Line 2: n whole numbers. Line 3: the target.
Output
The remaining values, or empty.
Example
Input
5 7 1 7 2 7 7
Output
1 2
Editor
C++
Hints
Put a dummy node in front of the head.
If prev->next holds the target, skip it and delete it; otherwise move prev on.
Solution explanation
The dummy node removes the special case for the head.
Show solution
#include <iostream>
using namespace std;
struct Node {
int value;
Node* next;
Node(int v) : value(v), next(nullptr) {}
};
int main() {
int n;
cin >> n;
Node* head = nullptr;
Node* tail = nullptr;
for (int i = 0; i < n; i++) {
int x;
cin >> x;
Node* node = new Node(x);
if (!head) head = tail = node;
else { tail->next = node; tail = node; }
}
int target;
cin >> target;
Node dummy(0);
dummy.next = head;
Node* prev = &dummy;
while (prev->next) {
if (prev->next->value == target) {
Node* gone = prev->next;
prev->next = gone->next;
delete gone;
} else {
prev = prev->next;
}
}
if (!dummy.next) cout << "empty" << endl;
for (Node* c = dummy.next; c; c = c->next) cout << c->value << (c->next ? " " : "\n");
return 0;
} Output
Answer
You can practice without logging in. Log in to save completion.
Save your progress
You're practising as a guest, so your progress won't be saved.
- Track every lab you complete
- Earn verifiable lab certificates
- See your progress in every module