Stack is data structure in programming language. Which store and retrieve data in LIFO (Last in First Out). Mostly this technique is used for storing of data in memory. This is very simple program to under stand working of stack in c++ language using class.
#include
<iostream.h>
#include <conio.h>
#include <stdlib.h>
class stack
{
private:
int stk[10];
int top;
public:
stack()
{
top=-1;
}
void push(int x)
{
if(top==10)
{
cout<<"Stack is
full "<<endl;
}
else
stk[++top]=x;
cout<<"Element
is inserted "<<x<<endl;
}
void pop(int x)
{
if(top=-1)
{
cout<<"Stack is
empty "<<endl;
}
else
stk[top--]=x;
cout<<"Element
is removed "<<x<<endl;
}
void display()
{
for(int i=0; i<=10;
i++)
{
cout<<"Element
are "<<stk[i];
}
}
};
void main()
{
int ch;
stack st;
while(1)
{
cout<<"1. Enter
1 for insert element \n2. Enter 2 for Delete element \n3. Enter 3 for Display
element \n4. Exit"<<endl;
cin>>ch;
switch(ch)
{
case 1:
cout<<"Enter
data"<<endl;
cin>>ch;
st.push(ch);
break;
case 2:
st.pop(ch);
break;
case 3:
st.display();
break;
case 4:
exit(0);
break;
}
}
getch();
}
Output result:-
Stack in C++ |
Post a Comment