资讯动态

用顺序表实现栈的基本操作

发布时间:2026/8/23 20:42:39 来源:尧图企业网站定制
栈的操作包括初始化栈入栈出栈判空销毁栈获取栈的长度获取栈顶元素。在C语言中首先引用头文件#includestdio.h #includestdlib.h #includestdbool.h接下来是栈的结构体定义typedef struct Stack{ int *data; int top; int init_capacity;}Stack;data指针指向第一个元素的位置top指的是栈顶元素的下标init_capacity指的是栈的容量。初始化栈Stack *create_stack(int init_capacity){ Stack *stack(Stack *)malloc(sizeof(Stack)); if(!stack){ printf(malloc fail); exit(1)} stack-data(int *)malloc(init_capacity*sizeof(int)); if(!stack-data){ printf(malloc fail); exit(1);} stack-init_capacityinit_capacity; stack-top-1; return stack;}判空bool is_empty(Stack *stack){ return !stack||stack-top-1;}获取栈中元素的个数int size(Stack *stack){ return !stack?0:stack-top1;获取栈顶元素不出栈bool peek(Stack *stack, int *val){ if(!stack || is_empty(stack)){ printf(错误栈为空或指针无效\n); return false; // 返回false程序不终止 } *val stack-data[stack-top]; return true; // 返回true表示成功 }入栈void push(Stack *stack,int value){ if(!stack){ return;} if (stack-top stack-init_capacity - 1) { stack-init_capacity * 2; stack-data (int*)realloc(stack-data, stack-init_capacity * sizeof(int)); if (!stack-data) { perror(realloc failed); exit(EXIT_FAILURE);}} stack-data[stack-top]value;}入栈操作时如果栈满的话可以直接返回也可以在代码中重新申请空间扩容。出栈int pop(Stack *stack){ if(!stack||is_empty(stack)){ exit(1);} return stack-data[stack-top--];}销毁栈void destroy_stack(Stack *stack){ if(stack){ free(stack-data); free(stack);}}exit()与return特性returnexit()作用对象仅作用于当前函数作用于整个程序执行结果返回到函数调用处程序继续执行直接终止整个程序退出到操作系统清理行为仅清理当前函数的局部变量会执行注册的清理函数如atexit、刷新缓冲区、关闭文件描述符等返回值意义返回给调用者可以是任意类型返回给操作系统0 成功非 0 失败头文件无需额外头文件需要#include stdlib.h

读完文章,也想定制专属网站?

尧图设计师 24 小时内与您沟通定制方案

免费获取报价