#include<iostream.h>
#include<process.h>
#include<conio.h>
class node
{
int d;
node *next;
friend class stack;
};
class stack
{
node *top;
public:
stack()
{
top=NULL;
}
void push();
int pop();
void print();
void peep();
void change();
int size();
};
void stack::push()
{
int num;
node *n;
cout<<"\nenter a number:";
cin>>num;
n=new node;
n->d=num;
n->next=top;
top=n;
cout<<num<<"is pushed into the stack\n";
}
int stack::pop()
{
if(top==NULL)
{
cout<<"\nstack underflow\n";
return 0;
}
int num=top->d;
node *d=top;
top=top->next;
delete d;
return num;
}
void stack::print()
{
node *a=top;
while(a!=NULL)
{
cout<<"\n"<<a->d;
a=a->next;
}
}
void stack::peep()
{
int pos,i,c=size();
cout<<"\nenter position:";
cin>>pos;
if(pos<1||pos>c)
cout<<"\nwrong position\n";
node *a=top;
for(i=0;i<pos-1;i++)
a=a->next;
cout<<pos<<"position element is"<<a->d;
}
void stack::change()
{
int pos,i,num,c=size();
node *a=top;
cout<<"\n enter the position:";
cin>>pos;
if(pos<1||pos>c)
cout<<"\n wrong position\n";
cout<<"\nenter a number:";
cin>>num;
for(i=0;i<pos-1;i++)
a=a->next;
a->d=num;
cout<<"\nnumber is changed\n";
}
int stack::size()
{
node *a=top;
int i=0;
while(a!=NULL)
{
i++;
a=a->next;
}
return i;
}
void main()
{
stack s;
int op,num;
while(1)
{
cout<<"\nstack elements are:\n";
s.print();
cout<<"\n1.push\n2.pop\n3.peep\n4.change\n5.size\n";
cout<<"\nenter your option\n";
cin>>op;
switch(op)
{
case 1:s.push();
break;
case 2:num=s.pop();
cout<<num<<"is popped element\n";
break;
case 3:s.peep();
break;
case 4:s.change();
break;
case 5:exit(0);
}
getch();
}
}
output :
stack elements are:
1.push
2.pop
3.peep
4.change
5.size
enter your option
1
enter a number: 1212
1212is pushed into the stack
stack elements are:
1212
1.push
2.pop
3.peep
4.change
5.size
enter your option
3
enter position: 1
1position element is1212
stack elements are:
1212
1.push
2.pop
3.peep
4.change
5.size
enter your option
2
1212is popped element
0 comments:
Post a Comment