Refill Stack using Node Implementation

2019-03-04 19:27发布

问题:

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;
}

回答1:

Stack::print shows a current "snapshop" of your stack, so it has no business modifying any of Stack'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 top member variable walk down the stack, initialize a local Node pointer to be the same as top and make the local pointer walk down the stack.

In other words, top should be read-only (immutable) within your print member function. To enforce that a member function must not modify any member variables, you can make the member function immutable by adding the const keyword at the end of your member function declaration.

Example:

// Const member function enforces that the Stack remain unmodified
void Stack::print() const
{
    Node *p = top; // Make p initially point to the top of the stack
    Type x;

    while(p != NULL) {
        x = p -> getinfo();
        cout << " " << x.color << " " << " " << x.counter << endl << endl;
        p = p->getNext(); // Make p walk down the stack to the next Node.
    } 
}


回答2:

If you want to print the contents of a stack and then push all the values back in the same order, I would suggest pushing the values onto a different stack after printing them. Then once the original stack is empty, pop all of the values from the second stack back into the original stack.