运用C语言实现栈的基本操作,其中包括入栈,出栈,清空栈,和对栈的,的基本介绍。判断栈是否为空,栈其实就是受到限制的线性表
#include <stdio.h>
#define STACK_SIZE 20//定义栈的大小;
typedef struct Stack{
int datas[STACK_SIZE];//栈数据保存区;
int top;//栈顶部位置标示,空栈时op=-1;
};
//初始化栈;
void initStack(struct Stack* stack){
stack->top=-1;
}
//清空栈;
void Empty(struct Stack* stack){
stack->top=-1;
}
//判断栈是否为空;
int isEmpty(struct Stack* stack){
return(stack->top==-1)? 1:0;
}
//判断栈是否已满;
int isFull(struct Stack* stack){
return (stack->top==STACK_SIZE-1)? 1:0;
}
//入栈操作;
int push(struct Stack* stack,int value){
//先判断栈是否已经满了;
if(isFull(stack)){
return 0;
}
stack->datas[++stack->top]=value;
return 1;
}
//出栈操作;先进后出,如子弹夹;
int pop(struct Stack* stack,int* retValue){
//先检查栈是否为空;;
if(isEmpty(stack)){
return 0;
}
*retValue=stack->datas[stack->top--];
return 1;
}
//读栈操作;
int getTop(struct Stack* stack,int* retValue){
if(isEmpty(stack)){
return 0;
}
*retValue=stack->datas[stack->top];
return 1;
}
//输出栈中的内容;
void printStack(struct Stack* stack){
if(isEmpty(stack)){
printf("当前是个空栈");
return;
}
printf("当前栈中的内容如下:\n");
for(int i=stack->top;i>-1;i--){
printf("[%d]:%d\n",i,stack->datas[i]);
}
printf("---------------------------\n");
}
int main(){
//初始化一个栈;
struct Stack stack;
initStack(&stack);
//添加数据,压栈;
for(int i=0;i<=10;i++){
push(&stack,i*10);//向栈中写入数据;
}
printStack(&stack);
printStack(&stack);
//出栈操作;
printf("出栈4个后内容如下");
int retValue;
for(int i=0;i<4;i++){
pop(&stack,&retValue);
}
printStack(&stack);
return 0;
}