#include <iostream>
using namespace std;
typedef char DataType;
struct StackType
{
DataType data;
StackType* p;
};
// return true if the stack is empty
bool isEmpty(StackType* st)
{
if(st==0)
return true;
else
return false;
}
// remove the top of the stack
void pop(StackType*& st)
{
StackType* tmp;
if(!isEmpty(st))
{
tmp=st->p;
delete st;
st=tmp;
}
}
// put data on top of the stack
void push(StackType*& st, DataType q)
{
StackType* tmp= new StackType;
tmp->data=q;
tmp->p=st;
st=tmp;
}
void main()
{
StackType* The_Stack;
push(The_Stack, ''A'');
pop(The_Stack);
if(isEmpty(The_Stack))
cout<<"It is empty"<<endl;
else
cout<<"It is NOT empty, but it should be.. :("<<endl;
}
Need help with my stack's isEmpty() function.
Hello! Im trying to code a stack, i have however run into a problem. I dont quite know how to check if the stack is empty. The method im using now dont work, im not sure why tough. Anyone know a better way to do this?
I have tried to search google for a stack algorithm but i can only find some realy advanced examples or a bunch of STL stuff. Anyone know a good resource for simple stacks and queues?
In this code i try to first push some data into the stack, the to pop it. Then i look if it is empty, but it is not, even tough i think it should :/
Thanks in advance for any input on this!
It''s been a while since I coded a stack, but the last time i used a struct, I passed it by reference, in your push and pop, you have *&, but just * in your isEmpty. I don''t know if you''ve tried this or not, but my stack code is long gone and I''m just digging around in my brain for a possible answer.
gatekeeper_prod
www.gatekeeperproductions.com
gatekeeper_prod
www.gatekeeperproductions.com
gatekeeper_prodwww.gatekeeperproductions.com
The stack should be empty before anything is even pushed onto it. Therefore, replace StackType* The_Stack with StackType* The_Stack = NULL and you''ll be fine.
The reason you have to do that is because in C/C++, variables are not initialized to a set value when they''re created, you have to treat them as having random and invalid values.
The reason you have to do that is because in C/C++, variables are not initialized to a set value when they''re created, you have to treat them as having random and invalid values.
This topic is closed to new replies.
Advertisement
Popular Topics
Advertisement