代码如下
#include"stdio.h"
#include"malloc.h"
#include"string.h"
#define Maxsize 100
typedef int datatype;
typedef struct{
datatype stack[Maxsize];
int top;
}SqStack;
SqStack *InitStack(){
SqStack *s;
s=(SqStack *)malloc(sizeof(SqStack));
if(!s){
printf("空间不足");
return NULL;
}else{
s->top=-1;
return s;
}
}
datatype GetTop(SqStack *s){
if(s->top == -1){
printf("栈是空的\n");
return 0;
}else{
return s->stack[s->top];
}
}
SqStack *Push(SqStack *s,datatype x){
if(s->top == Maxsize-1){
printf("栈是满的\n");
return NULL;
}else{
s->top++;
s->stack[s->top] = x;
return s;
}
}
datatype Pop(SqStack *s){
if(s->top == -1){
printf("栈已经空了\n");
return 0;
}
s->top--;
return s->stack[s->top+1];
}
datatype SqStackEmpty(SqStack *s){
if(s->top == -1){
printf("栈是空的\n");
return 1;
}else{
printf("栈不是空栈\n");
return 0;
}
}
void display(SqStack *p){
int t;
t=p->top;
if(p->top == -1){
printf("栈是空的\n");
}else{
while(t!=-1){
printf("%d->",p->stack[t]);
t--;
}
}
}
main(){
int arr[8] = {1,2,3,4,5,6,7,8},i;
SqStack *p;
p = InitStack();
for(i=0;i<8;i++)
Push(p,arr[i]);
printf("新栈的元素是\n");
display(p);
printf("\n");
printf("栈顶的元素是");
printf("%d",GetTop(p));
printf("\n");
printf("判别是否为空栈?:");
SqStackEmpty(p);
printf("\n");
printf("出栈后栈里的元素是");
display(p);
printf("\n");
}