Question
The following takes a user given number and generates a stack of random colors based on it: red, yellow, green, black and blue. Please provide
The following takes a user given number and generates a stack of random colors based on it: red, yellow, green, black and blue. Please provide code, in which the user can then choose what color to remove and using ONLY stack functions remove all objects of that color. All objects in the stack that are NOT of that color are returned in the same order they were in prior to the color removal. The original code is below.
#include
#include
#include
#include
using namespace std;
template
//stack class
class Stack
{
//declaraing data variable
public:
T *st;//stack variable
int max_size;//to store the max size of stack
int top;//which points to current element in stack
int current;//variable to store current size
//constructor
Stack(int size)
{
//initializing variable
max_size = size;
//creating array
st = new T[max_size];
top = -1;
current = 0;
}
//method to add to stack
void push(T a)
{
if (top + 1 < max_size)//checking overflow
{
st[top + 1] = a;//assigning pointer
top++;
current++;
}
}
//method to show stack contents
void show()
{
int i = 0;
while (i <= top)
{
cout << st[i] << endl;
i++;
}
}
//method to remove element from stack
T* pop()
{
if (current != 0)//checking underflow
{
current--;
top--;
return st[top + 1];//returning pointer without freeing space
}
}
//method to return length of stack
int length()
{
return current;
}
//method to clean the stack, deletes all elements of the stack
void empty()
{
while (top > -1)
{
delete st[top];
top--;
current--;
}
}
};
int main()
{
string a[5] = { "red","yellow","green","black","blue" };
int n;
//asking user input
cout << "Enter stack container size (min :10 and max: 25):";
cin >> n;
//creating stack
Stack
//randomly adding n marbles to stack
int i = 0;
while (i < n)
{
int r = rand() % 5;//finding random marble to place
if (r < 0)r = r * -1;
s->push(a[r]);
i++;
}
cout << "Contents added to stack: ";
//DISPLAYING STACK
s->show();
return 0;
}
Step by Step Solution
There are 3 Steps involved in it
Step: 1
Get Instant Access to Expert-Tailored Solutions
See step-by-step solutions with expert insights and AI powered tools for academic success
Step: 2
Step: 3
Ace Your Homework with AI
Get the answers you need in no time with our AI-driven, step-by-step assistance
Get Started