实验完整代码
#include<stdio.h>
#include<malloc.h>
#define MAXSIZE 20
//顺序栈
typedef int datatype;
typedef struct{
datatype data[MAXSIZE];
int top;
}Seqstack;
//初始化栈
Seqstack *Init(){
Seqstack *s;
s=(Seqstack *)malloc(sizeof(Seqstack));
s->top=-1;
return s;
}
//判断栈空
int StackEmpty(Seqstack *s){
if(s->top==-1){
return 1;
}
else{
return 0;
}
}
//判断栈满
int StackFull(Seqstack *s){
if(s->top==MAXSIZE-1){
return 1;
}
else{
return 0;
}
}
//入栈
void Push(Seqstack *s,int x){
if(s->top==MAXSIZE-1){
printf("栈满!\n");
}
else{
s->top++;
s->data[s->top]=x;
printf("%d入栈成功!\n",x);
}
}
//出栈
int Pop(Seqstack *s){
int x;
if(StackEmpty(s)){
printf("栈空!\n");
return 0;
}
else{
x=s->data[s->top];
printf("当前出栈元素为:%d\n",x);
s->top--;
return 1;
}
}
//取栈顶元素
int PopTop(Seqstack *s){
int x;
if(StackEmpty(s)){
printf("栈空!\n");
return 0;
}
else{
x=s->data[s->top];
printf("当前栈顶元素为:%d\n",x);
return 1;
}
}
//测试
int main(){
Seqstack *stack;
stack=Init();
Push(stack,1);
Push(stack,2);
Push(stack,3);
Pop(stack);
PopTop(stack);
}
实验结果