#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define MAX 100
typedef struct
{
char name[20];
float score;
}SElemType;
typedef struct stack
{
SElemType *data;
int top;
int stackSize;
}SqStack;
int initSqStack(SqStack *S,int max)
{
S->data=(SElemType *)malloc(max*sizeof(SElemType));
if(!S->data){printf("空间申请失败!");exit(0);}
S->top=-1;
S->stackSize=max;
return 1;
}
int SqStackEmpty(SqStack S)
{
if(S.top=-1) return 0;
else return 1;
}
int SqStackGetTop(SqStack S,SElemType *e)
{
if(SqStackEmpty(S)) return 0;
*e=S.data[S.top];
return 1;
}
int SqStackLength(SqStack S)
{
return S.top+1;
}
int Push(SqStack *S,SElemType e)
{
if(S->stackSize==S->top+1) return 0;
S->top++;
S->data[S->top]=e;
return 1;
}
int Pop(SqStack *S,SElemType *e)
{
if(SqStackEmpty(*S)) return 0;
*e=S->data[S->top];
S->top--;
return 1;
}
int SqStackTraverse(SqStack S)
{
int k;
if(SqStackEmpty(S)){ return 0;}
for(k=S.top;k>=0;k--)
{printf("%s %7.2f\n",S.data[k].name,S.data[k].score);}
return 1;
}
void createSqStack(SqStack *S,int max)
{
SElemType x;
int yn;
initSqStack(S,max);
do{
printf("请输入进栈的学生数据:");
scanf("%s%f",x.name,&x.score);
Push(S,x);
printf("继续输入吗?yes=1,no=0:");
scanf("%d",&yn);
}while(yn);
}
int main()
{
SqStack S;
SElemType e1,e2,e3,e4,etop;
strcpy(e1.name,"A");
strcpy(e2.name,"B");
strcpy(e3.name,"C");
strcpy(e4.name,"D");
e1.score=87.44;
e2.score=69.22;
e3.score=56.33;
e4.score=89.22;
initSqStack(&S,10);
Push(&S,e1);Push(&S,e2);Push(&S,e3);Push(&S,e4);
SqStackTraverse(S);
printf("当前栈长:%d\n",SqStackLength(S));
SqStackGetTop(S,&etop);
printf("栈顶元素%s,%7.2f:\n",etop.name,etop.score);
Pop(&S,&etop);
SqStackTraverse(S);
printf("当前栈长:%d\n",SqStackLength(S));
}
运行结果
![在这里插入图片描述](https://i-blog.csdnimg.cn/blog_migrate/8935fa517a5dfdff7fbc2cbc6e363288.png)