栈的基本操作(C语言实现)

运用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;
}

 

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

外太空的莫扎特

在校生穷逼一个,呜呜呜

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值