Code:
#define size 10
class stack
{
int stck[size];
int tos;
public:
stack();
void push(int x);
int pop();
};
Do you mean for your stck data member to be an array (see above highlight in red)? Following code makes that assumption.
Code:
stack::stack()
{
cout<<"constructing stack:\n";
tos=0;
}
void stack::push(int x)
{
if(tos>=size)
{
cout<<"stack is full:\n";
return;
}
tos++;
stck[tos]=x;
}
Your push function starts at the wrong place. Your constructor sets tos to 0. When calling push for the first time, tos gets incremented to 1 and then we set stck[1]. Well... what happened to stck[0]? We have lost one of the available slots to store information. This also means that when tos is 9, we increment it to 10 and then set stck[10] which is an invalid array index.
Usually when I see stacks get implemented, the top gets set to -1 and the push looks something like:
Code:
void stack::stack()
{
tos = -1;
}
void stack::push(int x)
{
if(tos+1==size)
{
cout<<"stack is full:\n";
return;
}
stck[++tos]=x;
}
I would then implement the pop function like so:
Code:
int stack::pop()
{
if(tos==-1)
{
cout<<"stack is empty:\n";
return 0;
}
return stck[tos--];
}
I would also implement an IsEmpty function so you would not have to rely upon getting an "is empty" message and an automatic return value of 0 in the for loop in main during the pop operations.
Code:
bool stack::IsEmpty()
{
return tos == -1;
}
...
while( !s1.IsEmpty() && !s2.IsEmpty() ) // Changed from a for loop
{
s1.pop();
s2.pop();
}
Code:
int main()
{
stack s1,s2;
int i,tos;
clrscr();
cout<<"after push operation:\n";
for(i=0;i<=tos;i++)
{
s1.push(i);
s2.push(i);
}
...
tos is never initialized in main before its use. It's also a little confusing since you have a private member variable with the same name in your class. Also, the <= in the first for loop should be a < (assuming tos is meant to be initialized to size) unless it is your intention to test the "stack is full" message.
Note: It would be extremely easy to turn this into a templated class where both the type and the default stack size could be given as template parameters. Could be done in a minute.