使用vs2022手搓的,语法是c语言外加一点点c++
#include <iostream>
#define MaxSize 50
#define OK 1
#define ERROR 0
#define OVERFLOW -1
#define scanf scanf_s
typedef int Status;
typedef struct {
int *base;
int *top;
int StackSize;
}SqStack;
//初始化
Status InitStack(SqStack &S) {
S.base = new int[MaxSize];
if (!S.base) {
return ERROR;
}
S.top = S.base;
S.StackSize = MaxSize;
return OK;
}
//判断是否为空,空返回true,非空返回false
bool IsEmpty(SqStack S) {
if (S.base==S.top) return true;
return false;
}
//判断是否满,满返回true,没满返回false
bool IsFull(SqStack S) {
if (S.top - S.base == S.StackSize) {
return true;
}
return false;
}
//清空
Status StackClear(SqStack &S) {
if (S.base) S.top = S.base;
return OK;
}
//销毁
Status StackDestory(SqStack &S) {
if (S.base) {
delete S.base;
}
S.base = NULL;
S.top = S.base;
S.StackSize = 0;
return OK;
}
//入栈
Status Push(SqStack &S,int e) {
if (IsFull(S)) {
return ERROR;//栈满
}
*S.top++ = e;
return OK;
}
//出栈
Status Pop(SqStack &S, int &e) {
if (IsEmpty(S)) {
return ERROR;
}
e = *--S.top;
return OK;
}
//取栈顶元素
int GetTop(SqStack S) {
if (!IsEmpty(S)) {
return *(S.top - 1);//返回栈顶元素,栈顶指针不变
}
}
//输出栈元素
void PrintStack(SqStack S) {
if (IsEmpty(S)) {
printf("栈为空\n");
}
while (S.base != S.top) {
printf("%d ", *S.base);
++S.base;
}
printf("\n");
}
int main()
{
SqStack S; int n,i,e;
InitStack(S);
printf("请输入栈元素的个数:\n");
scanf("%d", &n);
printf("请输入栈元素内容:\n");
for (i = 0; i < n; i++) {
int j;
scanf("%d", &j);
Push(S, j);
}
printf("此时栈为:");
PrintStack(S);
printf("请输入出栈元素内容:\n");
scanf("%d", &e);
Pop(S, e);
printf("此时栈为:\n");
PrintStack(S);
printf("取出栈顶元素:\n");
printf("%d", GetTop(S));
}