﻿ C++ Delete all occurrences of an item in a stack

# C++ Stack Exercises: Delete all occurrences of an item in a stack

## C++ Stack: Exercise-13 with Solution

Write a C++ program to delete all occurrences of an item in a stack using arrays.

Test Data:
Input some elements onto the stack:
Stack elements are: 5 2 2 4 7
Remove 2 from the said stack:
Stack elements are: 5 4 7

Sample Solution:

C++ Code:

``````#include <iostream>

using namespace std;
#define MAX_SIZE 15 // Maximum size of stack

class Stack {
private:
int top; // Index of top element
int arr[MAX_SIZE]; // Array to store elements
public:
Stack() {
top = -1; // Initialize top index to -1 (empty stack)
}

bool push(int x) {
if (isFull()) {
cout << "Stack overflow" << endl;
return false;
}
// Increment top index and add element to array
arr[++top] = x;
return true;
}
int pop() {
if (isEmpty()) {
cout << "Stack underflow" << endl;
return 0;
}
return arr[top--];
}

int peek() {
if (isEmpty()) {
cout << "Stack is empty" << endl;
return 0;
}
return arr[top];
}

bool isEmpty() {
// Stack is empty if top index is -1
return (top < 0);
}

bool isFull() {
// Stack is full if top index is equal to MAX_SIZE - 1
return (top >= MAX_SIZE - 1);
}

void display() {
if (top < 0) {
cout << "Stack is empty" << endl;
return;
}
cout << "\nStack elements are: ";
for (int i = top; i >= 0; i--)
cout << arr[i] << " ";
cout << endl;
}
void delete_specific_element(Stack& stk, int element) {
if (stk.isEmpty()) {
cout << "Stack is empty." << endl;
return;
}

int size = stk.top + 1;
int temp[size];
int count = 0;

// Copy stack elements into a temporary array
while (!stk.isEmpty()) {
int current = stk.pop();
if (current != element) {
temp[count++] = current;
}
}
// Push non-matching elements back onto the stack
for (int i = count-1; i >= 0; i--) {
stk.push(temp[i]);
}
}
};

int main() {
Stack stk;
cout << "Input some elements onto the stack:";
stk.push(7);
stk.push(4);
stk.push(2);
stk.push(2);
stk.push(5);
stk.display();
cout << "\nRemove 2 from the said stack:";
stk.delete_specific_element(stk, 2);
stk.display();
cout << "\nInput two more elements onto the stack:";
stk.push(7);
stk.push(5);
stk.display();
cout << "\nRemove 7 from the said stack:";
stk.delete_specific_element(stk, 7);
stk.display();
cout << endl;
}
``````

Sample Output:

```Input some elements onto the stack:
Stack elements are: 5 2 2 4 7

Remove 2 from the said stack:
Stack elements are: 5 4 7

Input two more elements onto the stack:
Stack elements are: 5 7 5 4 7

Remove 7 from the said stack:
Stack elements are: 5 5 4
```

Flowchart:   CPP Code Editor: