#include<iostream.h>
#include<conio.h>
class stack
{
int data;
stack *next,*prev;
public:
void push(int);
int pop();
void display();
};
stack *bottom,*top;
/* push function*/
void stack::push(int num)
{
if((bottom==NULL)&&(top==NULL))
{
top=bottom=new stack;
top->data=num;
top->next=NULL;
top->prev=NULL;
}
else
{
top->next=new stack;
top->next->data=num;
top->next->prev=top;
top->next->next=NULL;
top=top->next;
}
}
/* display
function*/
void stack:: display()
{
stack *q=bottom;
if(bottom==NULL)
{
cout<<"\n\nStack is
empty";
}
else {
while(q!=NULL)
{
cout<<"\t "<<q->data;
q=q->next;
}
}
}
/*pop
function*/
int stack::pop()
{ int result;
if((bottom==NULL)&&(top==NULL))
{
return -1;
}
result=top->data;
top=top->prev;
if(top!=NULL)
{
delete(top->next);
top->next=NULL;
return result;
}
else
{
delete(bottom);
bottom=NULL;
return result;
}
}
/*main()
function*/
void main()
{
stack n1;
int ch;
char c;
do
{
clrscr();
cout<<"\n 1: PUSH 2:
DISPLAY 3: POP";
cout<<"\n\n Enter Your Choice: ";
cin>>ch;
switch(ch)
{
case 1:
cout<<"\n\n Enter Any number: " ;
int num;
cin>>num;
n1.push(num);
break;
case 2:
n1.display();
break;
case 3:
int n=n1.pop();
if(n==-1)
{
cout<<"\n\n Stack is empty";
}
else
{
cout<<"\n\n Popped Item is: "<<n;
}
break;
default:
cout<<"\n wrong selection";
break;
}
cout<<"\n\n Do you want to continue(y/n): ";
cin>>c;
}
while(c=='y');
}
No comments:
Post a Comment