I’m having a hard time refilling the stack after i take it all off in order to print it out. I am using node implementation so i think this fact is what is confusing me. Any suggestions would be appreciated, thank you.
This is my original stack::print()
// Function to print Gumball info field (color and counter)
void Stack::print()
{
Node *p;
Type x;
while(top != NULL) {
p = top;
x = p -> getinfo();
cout << " " << x.color << " " << " " << x.counter << endl << endl;
top = p -> getnext();
}
return;
}
This is my stack with my attempt to loop and store in temp. It compiles but still is not working as suppose to
void Stack::print()
{
Node *p,*q;
Type x,x_temp;
while(top != NULL) {
p = top;
x = p -> getinfo();
cout << " " << x.color << " " << " " << x.counter << endl << endl;
x_temp = x;
q = top;
top = p -> getnext();
}
while(top != NULL) {
q -> setinfo(x_temp);
q -> setnext(top);
top = q;
}
return;
}
Stack::printshows a current “snapshop” of your stack, so it has no business modifying any ofStack‘s member variables. There’s no need to make a “backup” of the stack and to restore it. You just have to walk down the stack in a manner that doesn’t disturb the stack.Instead of making the
topmember variable walk down the stack, initialize a localNodepointer to be the same astopand make the local pointer walk down the stack.In other words,
topshould be read-only (immutable) within yourprintmember function. To enforce that a member function must not modify any member variables, you can make the member function immutable by adding theconstkeyword at the end of your member function declaration.Example: