Refill Stack using Node Implementation

后端 未结 2 730
灰色年华
灰色年华 2021-01-26 18:17

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 su

2条回答
  •  日久生厌
    2021-01-26 18:36

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

提交回复
热议问题