Saturday, February 7, 2015

Generic stack in C++

#include<iostream>
using namespace std;
union u
{
int i;
char c;
float f;
};
struct elmnt
{
u b;
int tag;
};
class stack
{
public:
int top;
elmnt e[10],r,t;
void push(elmnt r);
elmnt pop();
stack()
{
top=-1;
}
};
void stack::push(elmnt r)
{
e[++top]=r;
}
elmnt stack::pop()
{
return(e[top--]);
}
int main()
{
stack s;
char ch;
int ctr=0,j;
do
{
cout<<"Press \n1 for int\n2 for char\n3 for float\n";
cin>>s.r.tag;
if(s.r.tag==1)
{
cin>>s.r.b.i;
s.push(s.r);
}
else if(s.r.tag==2)
{
cin>>s.r.b.c;
s.push(s.r);
}
else
{
cin>>s.r.b.f;
s.push(s.r);
}
ctr++;
cout<<"Press y for more:";
cin>>ch;
}
while(ch=='y' || ch=='Y');
cout<<"\n\nThus the stack contains:\n";
for(j=0;j<ctr;j++)
{
s.t=s.pop();
if(s.t.tag==1)
cout<<s.t.b.i<<endl;
else if(s.t.tag==2)
cout<<s.t.b.c<<endl;
else
cout<<s.t.b.f<<endl;
}
}

No comments:

Post a Comment

Contributors

Translate