How to Implement Stack using Array

/*implement stack using array */
#include<iostream.h>
#include<conio.h>
#define MAX 10
class stack
{
int s[MAX];
int top;
public:
stack()
{
top=-1;
}

void push(int );
int pop();
int isfull();
int isempty();
void display();
};
void stack:: push(int x)
{
if(isfull()==1)
{
cout<<“\n stack full”;
return;
}
else
{
top++;
s[top]=x;
}
}
int stack:: pop()
{
int ele=0;
if(isempty()==1)
{
cout<<“\n stack empty “;
return ele;
}
else
{
ele=s[top];
top–;
}
return ele;
}
void stack::display()
{
int i;
for(i=0;i<=top;i++)
cout<<“\n”<<s[i];
}
int stack:: isempty()
{
int i=0;
if(top==-1)
i=1;
return i;
}
int stack:: isfull()
{
int i=0;
if(top==MAX)
i=1;
return i;
}

void main()
{
stack s1;
int x;
int ch;
clrscr();
do
{
cout<<“\n\n1.push\n2.pop\n3.display\n4.exit”;
cout<<“\n Enter Choice “;
cin>>ch;
switch(ch)
{
case 1:
cout<<“\n enter element to insert “;
cin>>x;
s1.push(x);
break;
case 2:
cout<<“\n poped element is “<<s1.pop();
break;
case 3:
s1.display();
break;

}
}while(ch!=4);
}

Leave a Reply