#include<stdlib.h> #include<stdio.h> #include<string.h> //引入头文件 #define MAXLEN 20 //宏定义 typedef struct { //节点定义 char name[10]; int age; }SD; typedef struct stack{ //栈定义 SD sd[MAXLEN]; int top; }StackType; StackType *Init(){ //栈初始化 StackType *p; if(p=(StackType *)malloc(sizeof(StackType))){ p->top=0; return p; } return NULL; } int IsEmpty(StackType *s){ if(s->top==0) return 1; else return 0; } int IsFull(StackType *s){ if(s->top==MAXLEN) return 1; else return 0; } int Push(StackType *s,SD sd){ //进栈 if((s->top+1)>MAXLEN){ printf("栈已满"); return 0; } s->sd[++s->top]=sd; return 1; } SD Pop(StackType *s){ //出栈 if(s->top==0){ printf("栈已空"); exit(0); } return(s->sd[s->top--]); } void Free(StackType *s){ if(s) free(s); } void main(){ StackType *s; SD sd1,sd2; s=Init(); printf("入栈: 输入姓名 年龄\n"); do{ scanf("%s",&sd1.name); if(strcmp(sd1.name,"0")==0) break; //控制输入结束 else { scanf("%d",&sd1.age); Push(s,sd1); } }while(1); printf("出栈: \n"); getchar(); do{ sd2=Pop(s); printf("%s %d\n",sd2.name,sd2.age); }while(1); Free(s); }
栈的基本操作
最新推荐文章于 2022-05-07 17:27:38 发布