#include
#include
using namespace std;
#define STACK_INIT_SIZE 100
#define STACK_SPACE_INCR 20
#define TRUE 1
#define FALSE 0
typedef int SElemType;
typedef int Status;
struct SqStack
{
SElemType *base;
int top;
int stackSize;
};
Status InitStack(SqStack &S)
{
S.base = (SElemType *)malloc(STACK_INIT_SIZE*sizeof(SElemType));
if (!S.base)
{
return FALSE;
}
S.top = 0;
S.stackSize = STACK_INIT_SIZE;
return TRUE;
}
Status StackIsEmpty(SqStack S)
{
if (!S.top)
return TRUE;
else
return FALSE;
}
void ClearStack(SqStack & S)
{
if (S.base)
free(S.base);
S.top = 0;
S.stackSize = 0;
}
int StackLength(SqStack S)
{
return S.top;
}
void PrintStack(SqStack S)
{
int i;
cout<<"栈长度为"<for (i = 0; i < S.top; i++)
{
cout<}
cout<}
Status Push(SqStack &S, SElemType e)
{
if (S.top == S.stackSize)
{
//栈空间已满,重新获取空间
S.base = (SElemType *)realloc(S.base, (S.stackSize+STACK_SPACE_INCR)*sizeof(SElemType));
if (!S.base)
{
return FALSE;
}
S.stackSize += STACK_SPACE_INCR;
}
S.base[S.top] = e;
S.top++;
return TRUE;
}
Status Pop(SqStack &S, SElemType &e)
{
if (TRUE == StackIsEmpty(S))
{
return FALSE;
}
S.top--;
e = S.base[S.top];
return TRUE;
}
Status InitStackInput(SqStack &S)
{
SElemType n;
cout<<"请输入数据,以-1结束:"<while (1)
{
cin>>n;
if (n == -1)
break;
Push(S, n);
}
return TRUE;
}
int main()
{
int m;
SElemType e;
SqStack s;
InitStack(s);
do
{
cout<cout<<"所有操作如下:"< cout<<"1. 采用顺序存储实现栈的初始化操作"< cout<<"2. 采用顺序存储实现栈的入栈操作"< cout<<"3. 采用顺序存储实现栈的出栈操作"< cout<<"4. 打印栈中所有数据"< cout<<"-1.退出"< cout<<"请选择:"< cin>>m;
switch(m)
{
case 1:
InitStackInput(s);
break;
case 2:
cout<<"输入入栈的数据:"<cin>>e;
Push(s, e);
break;
case 3:
if (TRUE == Pop(s, e))
cout<<"出栈的数据为:"<else
cout<<"出栈失败"<break;
case 4:
PrintStack(s);
break;
case -1:
break;
default:
cout<<"没有该选项!"<break;
}
}while (m != -1);
ClearStack(s);
return 0;
}
g++编译通过, 编写了main函数以测试出入栈的功能, 运行结果正确
望采纳, 谢谢~