好的,所以我编辑了我的代码,但我仍有两个问题:
但这是我的代码:
#include <iostream>
using namespace std;
struct stack
{
int data[5];
int top;
};
void push (int a, stack &S)
{
S.top++;
if (S.top<5)
{
S.data[S.top]=a;
}
else cout<<"Stack is full!!!"<<endl; S.top--;
}
int pop(stack &S)
{
if (S.top==-1)
{
cout<<"Stack is empty!"<<endl;
}
else
{
int temp=S.data[S.top];
S.data[S.top]=NULL;
S.top--;
return temp;
}
}
bool isEMPTY(stack &S)
{
if (S.top==-1)
return true;
else return false;
}
bool isFULL(stack &S)
{
if (S.top==5)
return true;
else return false;
}
int main()
{
stack S = { {}, -1 };
push(5,S); cout<<"5 is pushed \n"<<endl;
push(3,S); cout<<"3 is pushed \n"<<endl;
push(1,S); cout<<"1 is pushed \n"<<endl;
push(2,S); cout<<"2 is pushed \n"<<endl;
push(6,S); cout<<"6 is pushed \n"<<endl;
push(7,S); cout<<"7 is pushed \n"<<endl;
cout<<pop(S)<<"is popped\n"<<endl;
cout<<pop(S)<<"is popped\n"<<endl;
cout<<pop(S)<<"is popped\n"<<endl;
return 0;
}
所以,第一个问题是,当我弹出时,我得到一个“完全随机的值”并且它不像LIFO。
其次,我实际上打算插入6个值,当我已经有最大值= 5时,输出实际上显示了6个值。
答案 0 :(得分:2)
stack S;
由于stack
是POD,因此上述行不会初始化成员top
。因此,在top
和push
函数中使用未初始化的pop
会调用未定义的行为。
写下这个:
stack S {}; //must be compiled in C++11 mode, else write : stack S = stack();
此值初始化S
及其成员,即top
初始化为0
。其余的代码可能仍然有其他问题,但至少你已经解决了正确的初始化问题。 如果您使用0
作为top
的初始值,则会相应地写出push
和pop
的逻辑!
修复后,在推送和从堆栈中弹出值之前检查top
的值,因为成员数组最多可以有{{} 1}}元素,当它为空时你不能弹出更多的元素。你必须保持这些不变量。
答案 1 :(得分:1)
我没有看到创建类型堆栈对象的位置以及如何初始化数据成员top。 另外,请使用nto帐户,成员函数push不会检查是否尝试在数组之外添加项目。
您应该按以下方式定义对象
stack S = { {}, -1 };
答案 2 :(得分:1)
else cout<<"Stack is full!!!"<<endl; S.top--;
与:
相同else
{
cout<<"Stack is full!!!"<<endl;
}
S.top--;
作为一般规则,尽量避免:编写if / else而不使用大括号,并避免在同一行中编写多行代码。
答案 3 :(得分:0)
错误是:
stack S;
S.top = -1;
for(int i = 0; i < 5; i++)
{
S.data[i] = 0;
}
stack S;
S.top = -1;
for(int i = 0; i < 5; i++)
{
S.data[i] = 0;
}