Code Example:

#include "stdio.h"
#include "stdlib.h"

#define STACK_SIZE 10

typedef struct Stack {
    char items[STACK_SIZE];  // 栈中数据
    int top;  // 栈顶位置
} Stack;


int init_stack(Stack *stack) {
    /**
     * 初始化栈:将栈顶指针置为-1
     */
    if (stack != NULL) {
        stack->top = -1;
        return 1;
    }
    return 0;
}

int push(Stack *stack, char item) {
    /**
     * 入栈操作:如果栈没满,入栈
     */
    if (stack->top < STACK_SIZE - 1) {  // 栈未满
        stack->top++;
        stack->items[stack->top] = item;
        return 1;
    }
    printf("\n栈满,数据'%c'并没有被插入", item);
    return 0;
}

char pop(Stack *stack) {
    /**
     * 出栈操作:如果栈不为空,出栈
     */
    char item;
    if (stack->top != -1) {  // 栈不为空
        item = stack->items[stack->top];
        stack->top--;
        return item;
    }
    printf("\n栈空,请勿再弹出数据");
    return NULL;
}


void main() {
    // 定义栈
    Stack *stack = malloc(sizeof(Stack));
    // 栈初始化
    init_stack(stack);
    // 入栈
    push(stack, 'a');
    push(stack, 'b');
    push(stack, 'c');
    push(stack, 'd');
    push(stack, 'e');
    push(stack, 'f');
    push(stack, 'g');
    push(stack, 'h');
    push(stack, 'i');
    push(stack, 'j');
    push(stack, 'k');
    // 出栈
    printf("\n出栈结果:");
    for (int i = 0; i < 11; ++i) {
        char item = pop(stack);
        if (item != NULL) {
            printf(" %c", item);
        }
    }
}

Output:

栈满,数据'k'并没有被插入
出栈结果: j i h g f e d c b a
栈空,请勿再弹出数据
  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值