How to perform push and pop in stack


Discuss the below:

Q: Extend the improved stack class stack2 so that the derived class stack would be also capable to store integers, strings, or pairs of integers. Model the pair by a structure with two integer-valued fields x and y.

In the main program, define several integers, strings, and pairs and demonstrate pushing them to and popping from your stack.#include


using namespace std;

class stack // a simple stack class
{
protected:
int top; // stack pointer
static const int MAX = 10; // stack size
private:
int st[MAX]; // stack array
public:
stack() // default constructor
{
top = -1;
}
void push(int n) // push method
{
st[++top] = n;
}
int pop() // pop method
{
return(st[top--]);
}
};

class stack2 : public stack // improved stack
{
public:
bool push(int n) // push now checks for stack overflow
{
if (top < MAX-1)
{
stack::push(n); // calling push() of superclass
return true;
}
else
return false;
}

bool pop(int &n) // new pop() prevents popping from empty stack
{
if (top >= 0)
{
n = stack::pop();
return true;
}
else
return false;
}
};

int main()
{
stack2 s;

if (! s.push(5))
cout << "end of stack has been reached" << endl;
if (! s.push(6))
cout << "end of stack has been reached" << endl;

int i, j;
if (! s.pop(i))
cout << "attempt to pop from empty stack" << endl;
if (! s.pop(j))
cout << "attempt to pop from empty stack" << endl;

cout << i << ' ' << j << endl;
}

Solution Preview :

Prepared by a verified Expert
C/C++ Programming: How to perform push and pop in stack
Reference No:- TGS01937257

Now Priced at $20 (50% Discount)

Recommended (95%)

Rated (4.7/5)