#define MAXSIZE 100
using namespace std;
#define ERROR 0
#define OK 1
#define OVERFLOW -2
typedef int SElemType;
typedef int Status;
typedef struct
{
SElemType *base;//栈底指针
SElemType *top;//栈顶指针
int stacksize; //栈可用的最大容量
} SqStack;
Status InitStack(SqStack &S)
{
S.base=new SElemType [MAXSIZE];//为顺序栈动态分配一个最大容量为MAXSIZE的数组空间
if(!S.base) exit(OVERFLOW);//存储分配失败
S.top=S.base;//top初始为base,空栈
S.stacksize=MAXSIZE;//stacksize置为栈的最大容量MAXSIZE
return OK;
}
Status CreateStack(SqStack &S,int n)// 创建一个包含n个正整数的栈
{
// InitStack(S);
for(int i=0;i<n;i++)
{
scanf("%d",S.top);
if(*S.top==-1) return OK;
printf("%d\n",*S.top);
S.top++;
}
return OK;
}
Status CreateStack11(SqStack &S)
{
// InitStack(S);
int n,i=0;
while(i<S.stacksize)
{
cin>>n;
if(n!=-1)
{
*S.top=n;
printf("%d\n",*S.top);// 只能打印一个数字,为啥子?
S.top++;
}
else break;
return OK;
}
}
Status Push(SqStack &S,SElemType &e)//入栈,插入元素e为新的栈顶元素
{//S是一个结构体变量,不是指针,S相当a=10;入栈一个数S发生变化了,因此需要&
if(S.top-S.base==S.stacksize) return ERROR; //栈满
*S.top++=e;
// *S.top=e;
// S.top++;
return OK;
}
Status Pop(SqStack &S,SElemType &e)//出栈,删除S的栈顶元素,用e返回其值
{//S,e均为实体变量,出栈后,其值均发生变化,要传回实参,故加&
if(S.top==S.base) return ERROR;//栈空
e=*--S.top;
return OK;
}
Status GetTop(SqStack S,SElemType &e)//返回S的栈顶元素,不修改栈顶指针
{
// if(S.top!=S.base)//栈非空
// return *(S.top-1);//返回栈顶元素的值,栈顶指针不变
if(S.top==S.base) return ERROR;
e=*(S.top-1);// 注意不是S.top--,不能修改S.top的值
return OK;
}
Status GetLength(SqStack S,int &Len)//栈长
{//S:值,也就是数组里的元素未修改,故不加&;e:需传回实参,故加&
if(S.top==S.base) return ERROR;
Len=S.top-S.base;//长度
return OK;
}
int main()
{ int n,Len;
SElemType e;
SqStack S;
InitStack (S);
printf("输入栈中的n个元素:");
scanf("%d",&n) ;
CreateStack(S,n);//建栈
// CreateStack11(S);
printf("输入要插入的元素e:");
scanf("%d",&e);
Push(S,e);//入栈
printf("入栈元素为:%d\n",e);
Pop(S,e); //出栈
GetTop(S,e);//返回S的栈顶元素,不修改栈顶指针
printf("出栈一次后栈顶元素的值为:%d\n",e);
GetLength(S,Len);//栈长
printf("栈长为:%d",Len);
}