我把它全部取下以便打印出来后,我很难重新填充堆栈。我正在使用节点实现,所以我认为这个事实让我感到困惑。任何建议将不胜感激,谢谢。
这是我原来的堆栈:: 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;
}
// 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;
}
答案 0 :(得分:1)
如果要打印堆栈的内容,然后以相同的顺序将所有值推回,我建议在打印后将值推送到不同的堆栈。然后,一旦原始堆栈为空,将第二个堆栈中的所有值弹回原始堆栈。
答案 1 :(得分:0)
Stack::print
显示了您的堆栈的当前“snapshop”,因此它无法修改任何Stack
的成员变量。没有必要对堆栈进行“备份”并恢复它。你只需要以不会打扰堆栈的方式走下堆栈。
不是让top
成员变量向下遍历堆栈,而是将本地Node
指针初始化为与top
相同,并使本地指针沿堆栈向下移动。
换句话说,top
在print
成员函数中应该是只读的(不可变的)。要强制成员函数不能修改任何成员变量,可以通过在成员函数声明的末尾添加const
关键字使成员函数不可变。
示例:
// 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.
}
}