Answered step by step
Verified Expert Solution
Link Copied!

Question

1 Approved Answer

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 *s = new Stack(n);//creating with size 3

//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

blur-text-image

Get Instant Access to Expert-Tailored Solutions

See step-by-step solutions with expert insights and AI powered tools for academic success

Step: 2

blur-text-image

Step: 3

blur-text-image

Ace Your Homework with AI

Get the answers you need in no time with our AI-driven, step-by-step assistance

Get Started

Recommended Textbook for

Transact SQL Cookbook Help For Database Programmers

Authors: Ales Spetic, Jonathan Gennick

1st Edition

1565927567, 978-1565927568

More Books

Students also viewed these Databases questions