当前位置: 首页 > news >正文

从零写栈:c语言版本

栈的接口的全代码

1, stack.h

#pragma once #include<stdio.h> #include<assert.h> #include<stdlib.h> #include<stdbool.h> //顺序表来建立栈 typedef int SLDateType ; typedef struct stack { SLDateType* a; int top; int capacity; }ST; //初始化 和 销毁 void STInit(ST* pst); void STDestroy(ST* pst); //进栈出栈 void STPush(ST* pst, SLDateType x); void STPop(ST* pst); //取栈顶数据 SLDateType STTop(ST* pst); // 判空 bool STEmpty(ST* pst); // 获取数据个数 int STSize(ST* pst);

2,stack.h

#include"stack.h" //初始化 和 销毁 void STInit(ST* pst) { assert(pst); pst->a = NULL; pst->capacity = 0; //当top指向的是结尾下一个 pst->top = 0; //当同top指向结尾 //pst->top = -1; } void STDestroy(ST* pst) { assert(pst); free(pst->a); pst->a = NULL; pst->capacity = 0; pst->top = 0; } //进栈出栈 void STPush(ST* pst, SLDateType x) { assert(pst); //检查数组空间够吗 if (pst->top == pst->capacity) { int newcapacity = pst->capacity == 0 ? 4 : pst->capacity * 2; SLDateType* temp = (SLDateType*)realloc(pst->a, newcapacity * sizeof(SLDateType)); if (temp == NULL) { perror("realloc fail"); return; } pst->a = temp; pst->capacity = newcapacity; } //扩容之后在进展 pst->a[pst->top] = x; pst->top++; } void STPop(ST* pst) { assert(pst); //为了不是空数组,要不怎么出栈啊 assert(pst->top > 0); pst->top--; } //取栈顶数据 SLDateType STTop(ST* pst) { assert(pst); assert(pst->top > 0); return pst->a[pst->top - 1]; } // 判空 bool STEmpty(ST* pst) { assert(pst); return pst->top == 0; } // 获取数据个数 int STSize(ST* pst) { assert(pst); return pst->top; }

3,注意事项、

top的不同指向

realloc函数的使用要传头指针 STDatetype* a;

4,知识点

- 当你调用 free(pst->a) 时

只需要传入当时申请时返回的首地址(也就是数组第一个元素的地址)

内存管理器就能根据记录找到整块内存并完整释放

在注销的时候直接free(pst->a)就可以数组全释放

http://www.jsqmd.com/news/478758/

相关文章:

  • window环境安装openclaw
  • Failed to create the npcap service: 0x8007007e
  • 三大Java工具库:Hutool vs Guava vs Commons
  • ubuntu下 apt安装tomcat
  • 2026论文降重盘点:AIGC严查下谁能活?
  • 从「设计优先」到「实践优先」:构建自学习 AI Agent 的技能生态系统
  • 起诉状不用求人了!1个工具直接生成
  • 以初心守安全,以专业赋自由|VR精灵:解锁无束缚的创作底气
  • 【Java八股锁机制的认识】synchronized和reentrantlock区分,锁升级机制
  • 30.05亿元!衣橱应用程序市场规模披露,智能穿搭生态潜力加速释放
  • Linux文件类型
  • 什么是管理
  • SRA166防静电防护服安装保养指南:避免机器人静电损伤的实操详解
  • 99个大模型在各个行业的应用的案例【2026最新】
  • “养虾”狂飙背后的企业安全隐患:当AI接管企业内网,谁来为它戴上“紧箍咒”?
  • 基于SpringBoot+Vue的活动策划网站毕设项目(完整源码+论文+部署)
  • 救命神器! 降AI率平台 千笔 VS PaperRed,本科生专属利器!
  • 什么是残差连接与归一化
  • 百考通AI毕业论文智能生成,让学术创作高效又专业
  • 清华首次揭露:AI图像编辑器的“视觉后门“如何轻松突破安全防线
  • 再谈《复利的力量》
  • 14-ORM-数据库操作-查询条件
  • 混频器在雷达模块中的作用及原理……
  • 大模型中量化是什么
  • Django中间件
  • 解决brew安装慢问题
  • 我看见ta拿着枪指着我的头
  • 斯坦福 CS336 从零构建大模型 (2025 春) - 第四讲:专家混合模型(Mixture of Experts, MoE)
  • Claude code学习记录
  • 性价比高的律师营销机构有啥特色?这3点让你秒懂!