Refill Stack using Node Implementation

梦想与她 提交于 2019-12-02 10:21:11

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!