Code:
while (topOfStack != NULL && topOfStack->next != NULL)
{
temp = topOfStack;
topOfStack = topOfStack->next; // Seems to be a problem here
delete temp;
}
you forgot to check if topOfStack->next even points to anything
plus you'll want to initialize the topOfStack->next to either point to something, or else = NULL (0)
One other thing is it's probably better to put your initialization for topOfStack into your constructor; and also to check for errors, i.e.:
Code:
<snip>
StackNode *topOfStack; //a pointer to the first node in stack
};
Code:
Stack::Stack()
{
try {
topOfStack = new StackNode;
} catch(...) {
topOfStack = NULL;
}
if(topOfStack != NULL) topOfStack->next = NULL;
}
or use 0 instead of NULL -
same thing, although some say it's better to use NULL, and some say it's better to use 0... beats me but they both work.
Plus it's easier to say
if(topOfStack)
than it is to say
if(topOfStack != NULL)
Also, if all you do in your catch(...) statement is set topOfStack to NULL or 0, then later you will have to be sure to always check if it points to anything, or if it is NULL.