// IMPLEMENTATION OF STACK USING ARRAYS
#include <iostream.h>
#include <conio.h>
#include <ctype.h>
#define size 100
int top = -1;
int flag = 0;
class stacks {
public:
void push(int *, int);
int pop(int *);
void display(int *);
};
/*----------- PUSH -----------*/
void stacks::push(int s[], int d)
{
if (top == size - 1)
flag = 0; // overflow
else {
flag = 1;
++top;
s[top] = d;
}
}
/*----------- POP ------------*/
int stacks::pop(int s[])
{
int popped;
if (top == -1) { // underflow
popped = 0;
flag = 0;
} else {
flag = 1;
popped = s[top];
--top;
}
return popped;
}
/*---------- DISPLAY ---------*/
void stacks::display(int s[])
{
if (top == -1)
cout << "Stack is empty";
else
for (int i = top; i >= 0; --i)
cout << "\n\t" << s[i];
}
/*============= MAIN =========*/
void main()
{
clrscr();
stacks stk;
int stack[size];
int data;
char choice; // must be char to match 'i','p','q'
int quit = 0;
/*--- SINGLE do-while LOOP ---*/
do {
cout << "\nPush->i Pop->p Quit->q";
cout << "\nInput the choice: ";
cin >> choice;
choice = tolower(choice);
switch (choice)
{
case 'i': // PUSH
cout << "\nInput the element to be pushed: ";
cin >> data;
stk.push(stack, data);
if (flag) {
cout << "\nAfter inserting";
stk.display(stack);
if (top == size - 1)
cout << "\nStack is full";
} else
cout << "\nStack overflow after pushing";
break;
case 'p': // POP
data = stk.pop(stack);
if (flag) {
cout << "\nData is popped: " << data;
cout << "\nRest data in stack is as follows:";
stk.display(stack);
} else
cout << "\nStack underflow";
break;
case 'q': // QUIT
quit = 1;
break;
default:
cout << "\nInvalid choice";
}
} while (!quit); // <-- matching while
getch();
}