/**
* 栈是一种数据结构,特点:先进后出
* 练习:使用全局变量模拟栈的操作
*/
#include <stdio.h>
#include <stdbool.h>
#include <assert.h>
//保护全局变量:在全局变量前加static后,这个全局变量就只能在本文件中使用
static int data[1024];//栈最多能保存1024个数据
static int count = 0;//目前已经放了多少个数(相当于栈顶位置)
//数据入栈 push
void push(int x){
assert(!full());//防止数组越界
data[count++] = x;
}
//数据出栈 pop
int pop(){
assert(!empty());
return data[--count];
}
//查看栈顶元素 top
int top(){
assert(!empty());
return data[count-1];
}
//查询栈满 full
bool full() {
if(count >= 1024) {
return 1;
}
return 0;
}
//查询栈空 empty
bool empty() {
if(count <= 0) {
return 1;
}
return 0;
}
int main(){
//入栈
for (int i = 1; i <= 10; i++) {
push(i);
}
//出栈
while(!empty()){
printf("%d ", top()); //栈顶元素
pop(); //出栈
}
printf("\n");
return 0;
}
网友评论