一个简单的栈实现

#include<stdbool.h>
#include<stdio.h>
#include<string.h>
#include<ctype.h>
#include<strings.h>
#include<stdlib.h>
#ifndef stack_h 
#define stack_h
#include <stddef.h> // for size_t

typedef int ele;//栈的类型 

// 定义栈结构体,包含栈顶指针、容量和当前元素数量等信息
typedef struct {
    ele* data;     // 栈内存储数据的数组
    size_t capacity; // 栈的总容量
    size_t count;   // 当前栈内元素数量
}zhan;
// 初始化栈,分配指定容量的内存空间
zhan space(size_t capacity) {
    zhan stack = {0};
    stack.capacity = capacity;
    stack.data = malloc(capacity * sizeof(*stack.data));
    if (!stack.data) {
        fprintf(stderr, "Failed to allocate memory for the stack.\n");
        exit(EXIT_FAILURE);
    }
    return stack;
}
// 销毁栈,释放栈占用的内存资源
void xiaohui(zhan* stack) {
    free(stack->data);
    stack->data = NULL;
    stack->capacity = 0;
    stack->count = 0;
}
// 压一个元素进栈
void in(zhan* stack, ele element) {
    if (isman(stack)) {
        fprintf(stderr, "Stack overflow. Cannot push element onto a full stack.\n");
        exit(EXIT_FAILURE);
    }
    stack->data[stack->count++] = element;
}
// 判断栈是否为空
int iskong(const zhan* stack) {
    return stack->count == 0;
}
// 判断栈是否已满
int isman(const zhan* stack) {
    return stack->count == stack->capacity;
}
// 从栈中弹出一个元素
ele out(zhan* stack) {
    if (iskong(stack)) {
        fprintf(stderr, "Stack underflow. Cannot pop from an empty stack.\n");
        exit(EXIT_FAILURE);
    }
    // 保存即将弹出的栈顶元素的值
    char top_element = stack->data[stack->count - 1];
    // 弹出操作:减少计数并将栈顶元素置为 '\0'
    stack->data[--stack->count] = '\0';
    // 返回栈顶元素的原值
    return top_element;
}
// 获取栈顶元素(但不弹出)
ele gettop(const zhan* stack) {
    if (iskong(stack)) {
        fprintf(stderr, "Stack is empty. Cannot get the top element.\n");
        exit(EXIT_FAILURE);
    }
    return stack->data[stack->count - 1];
}
#endif // stack_h
int main(){
    int tmp;
    zhan a=space(100);
    scanf("%d",&tmp);
    in(&a,tmp);
    printf("%d",gettop(&a));
    return 0;
}
 

  • 5
    点赞
  • 10
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值