栈的基本操作

 #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);
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值