6.1 Write a program to perform the following Stack operations using linked list .
Push
Pop
Clear
--------------------------------------------------------------------------------------------------------------------
#include<iostream>
using namespace std;
template<class t>
//const int size=5;
class stack
{
public:
t data;
stack *prev;
};
template<class t>
class stacks
{
//int stack[size];
stack<t> *top;
public:
stacks()
{
top=NULL;
}
void push(t n)
{
stack<t> *temp;
temp=new stack<t>;
temp->data=n;
temp->prev=top;
top=temp;
}
t pop()
{
t a;
if(top==NULL)
{
cout<<"underflow:\n";
return -1;
}
else
{
a=top->data;
top=top->prev;
return a;
}
}
void display()
{
cout<<"The data in stack is:\n";
while(top!=NULL)
{
cout<<top->data<<"\n^\n"<<endl;
top=top->prev;
}
}
int empty()
{
if(top==NULL)
return -1;
else
return 1;
}
void clear(){top=-1;}
};
int main()
{
char ch;
int n,n1;
stacks<int> s1;
do
{
cout<<"Enter if u want to push any element:\n";
cin>>ch;
if(ch=='y')
{
cout<<"Enter the element to be pushed:\n";
cin>>n;
s1.push(n);
}
}while(ch=='y');
do
{
cout<<"Enter if u want to pop any element:\n";
cin>>ch;
if(ch=='y')
{
n=s1.pop();
if(n==-1)
break;
cout<<"Popped element is : "<<n<<"\n";
}
}while(ch=='y');
if(s1.empty()==1)
{
cout<<"The stack after all operations:\n";
s1.display();
}
else
cout<<"NULL stack\n";
return 0;
}
---------------------------------------------------------------------------------------------------------------------