栈的演示1.

来源:互联网 发布:淘宝大学鹰图学院 编辑:程序博客网 时间:2024/05/17 03:22
#ifndef  __01STACK_H__
#define  __01STACK_H__
//分配栈里所使用的存储区
void stack_init();
//释放栈里所使用的存储区
void stack_deinit();
//判断是否栈已经被填满
int stack_full();
//判断栈里是否没有数字
int stack_empty();
//计算栈里包含的数字个数
int stack_size();
//向栈里放一个数字
void stack_push(int );
//从栈里获得一个数字(会把数字从栈里删除)
int stack_pop();
//获得下一个数字的数值但不删除它
int stack_top();
#endif    //__01STACK_H__


#include "01stack.h"
static int stack[STACK_SIZE];
static int num;
//分配栈里所使用的存储区
void stack_init() {
}
//释放栈里所使用的存储区
void stack_deinit() {
}
//判断是否栈已经被填满
int stack_full() {
return num == STACK_SIZE;
}
//判断栈里是否没有数字
int stack_empty() {
return !num;
}
//计算栈里包含的数字个数
int stack_size() {
return num;
}
//向栈里放一个数字
void stack_push(int val) {
if (num < STACK_SIZE) {
stack[num] = val;
num++;
}
}
//从栈里获得一个数字(会把数字从栈里删除)
int stack_pop() {
if (num > 0) {
num--;
return stack[num];
}
return -1;
}
//获得下一个数字的数值但不删除它
int stack_top() {
if (num > 0) {
return stack[num - 1];
}
return -1;

}


/*
   栈练习
   */
#include <stdio.h>
#include "01stack.h"
int main() {
int num = 0;
stack_init();
do {
printf("请输入一个数字:");
scanf("%d", &num);
if (num >= 0) {
if (!stack_full()) {
   stack_push(num);
}
}
else {
break;
}
} while (1);
printf("一共有%d个数字\n", stack_size());
while (!stack_empty()) {
printf("%d ", stack_pop());
}
printf("\n");
stack_deinit();
return 0;
}








































0 0