#include<stdio.h>
#include<stdlib.h>
#define STACK_INIT_SIZE 100
#define STACKINCREMENT 10
typedef struct{
char name[10];
int score;
}student;
typedef struct {
student *base;
student *top;
int stacksize;
}SqStack;
SqStack InintStack(SqStack &S){
S.base=(student *)malloc(STACK_INIT_SIZE *sizeof(student));
if(!S.base) exit(1);
S.top=S.base;
S.stacksize=STACK_INIT_SIZE;
printf("bulid succeed\n");
return S;
}
bool ClearStack(SqStack &S){
/*while(S.top){
S.top=NULL;
S.top--;
if(S.top==S.base)
S.top=S.base=NULL;
}*/
S.top=S.base;
return true;
}
bool DestoryStack(SqStack &S){
free(S.base);
return true;
}
bool IsStackEmpty(SqStack &S){
if(S.top==S.base)
return true;
else
return false;
}
int StackLength(SqStack &S){
return (S.top-S.base);
}
bool GetTop(SqStack &S,student &e){
if(S.top==S.base){
return false;
}
e=*(S.top-1);
return true;
}
bool Push(SqStack &S,student e){
//printf("%d\n",e.score);
if(S.top-S.base>=S.stacksize){
S.base=(student *)realloc(S.base,(S.stacksize+STACKINCREMENT)*sizeof(student));
if(!S.base) exit(1);
S.top=S.base+S.stacksize;
S.stacksize+=STACKINCREMENT;
}
* S.top=e;
S.top++;
return true;
}
bool Pop(SqStack &S,student &e){
if(S.top==S.base) return false;
e=*--S.top;
return true;
}
bool PrintStack(SqStack &S){
int i=0;
while((S.top-i)!=S.base){
i++;
printf("%s,%d\n",(*(S.top-i)).name,(*(S.top-i)).score);
}
return true;
}
int main(){
SqStack s;
InintStack(s);
int set,isclose;
student student_in,student_top;
/*student student[10];
for(int i=0;i<2;i++){
scanf("%s %d",student[i].name,&student[i].score);
Push(s,student[i]);
}
PrintStack(s);
*/
while(1){
set=0;
printf(" 1.插入学生\n 2.删除最后一个学生并输出\n 3.输出栈的长度\n 4.销毁栈\n 5.清空栈 \n 6.查询该栈是否为空 \n 7.输出最后一个学生\n 8.输出整个栈中的所有学生\n 9.建立栈(在销毁后重建)\n");
scanf("%d",&set);
switch(set){
case 1:printf("请输入学生的姓名和分数,用空格分隔\n");scanf("%s %d",student_in.name,&student_in.score);if(Push(s,student_in)) printf("插入成功\n");;break;
case 2:if(Pop(s,student_top))printf("%s,%d\n",student_top.name,student_top.score);else printf("栈里无学生\n");break;
case 3:printf("%d\n",StackLength(s));break;
case 4:if(DestoryStack(s)) printf("销毁成功\n");break;
case 5:if(ClearStack(s)) printf("清空成功\n");break;
case 6:if(IsStackEmpty(s)) printf("栈为空\n"); else printf("栈不为空\n");break;
case 7:if(GetTop(s,student_top))printf("%s,%d\n",student_top.name,student_top.score);else printf("栈里无学生\n");break;
case 8:PrintStack(s);break;
case 9:InintStack(s);break;
}
printf("结束输入0\n");
scanf("%d",&isclose);
if(!isclose) break;
}
return 0;
}
本文出自 “zjwzjw369” 博客,谢绝转载!
原文地址:http://zjwzjw369.blog.51cto.com/10388875/1660973