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

[数据结构]5. 栈-Stack

栈-Stack

  • 1. 介绍
  • 2. 栈的实现
    • 2.1 基于链表的实现
    • 2.2 基于数组的实现
  • 3. 栈操作
    • Create
    • Initilizate
    • Destory
    • Push
    • Pop
    • Top
    • Empty
    • Size

1. 介绍

栈(stack) 是一种遵循先入后出逻辑的线性数据结构。顶部称为“栈顶”,底部称为“栈底”。把元素添加到栈顶的操作叫作“入栈”,删除栈顶元素的操作叫作“出栈”。
请添加图片描述

2. 栈的实现

2.1 基于链表的实现

请添加图片描述请添加图片描述请添加图片描述

2.2 基于数组的实现

请添加图片描述请添加图片描述
请添加图片描述

3. 栈操作

Create

typedef int STDataType;
typedef struct Stack
{STDataType* a;int top;int capacity;
}ST;

Initilizate

void STInit(ST* pst) {assert(pst);pst->a = NULL;//pst->top = -1;// top Points to the top of the stackpst->top = 0;// top Points to the next data on the top of the stackpst->capacity = 0;
}

Destory

void STDestory(ST* pst) {assert(pst);free(pst->a);pst->top = pst->capacity = 0;
}

Push

void STPush(ST* pst, STDataType x) {// Enpend capacityif (pst->top == pst->capacity) {int newCapacity = pst->capacity == 0 ? 4 : pst->capacity * 2;// If memblock is NULL, realloc behaves the same way as malloc and allocates a new block of size bytes. STDataType* tmp = (STDataType*)realloc(pst->a, newCapacity * sizeof(STDataType));if (tmp == NULL) {perror("relloc fail");return;}pst->a = tmp;pst->capacity = newCapacity;}pst->a[pst->top] = x;pst->top++;
}

Pop

void STPop(ST* pst) {assert(pst);assert(!STEmpty(pst));pst->top--;
}

Top

STDataType STTop(ST* pst) {assert(pst);assert(!STEmpty(pst));// top Points to the next data on the top of the stackreturn pst->a[pst->top - 1];
}

Empty

bool STEmpty(ST* pst) {assert(pst);return pst->top == 0;
}

Size

int STSize(ST* pst) {assert(pst);return pst->top;
}

相关文章:

  • ​Android学习总结之handler中源码解析和场景回答
  • 计算机操作系统(七)详细讲解进程的组成与特性,状态与转换
  • 可视化数据图表怎么做?如何实现三维数据可视化?
  • 技术中台-核心技术介绍(微服务、云原生、DevOps等)
  • Prometheus+Grafana+AlertManager完整安装过程
  • YOLO v2:目标检测领域的全面性进化
  • 网络防空总结 各种攻击
  • 光流 | Matlab工具中的光流算法
  • acwing 4275. Dijkstra序列
  • JVM学习专题(二)内存模型深度剖析
  • 尚硅谷阳哥JVM
  • upload-labs通关笔记-第5关 文件上传之.ini绕过
  • CSS Grid布局:从入门到实战
  • 【windows server脚本每天从网络盘复制到本地】
  • AI世界的崩塌:当人类思考枯竭引发数据生态链断裂
  • 数据安全与权限管控,如何实现双重保障?
  • Vue3学习(组合式API——计算属性computed详解)
  • Android学习总结之Glide自定义三级缓存(面试篇)
  • 关于 Golang GC 机制的一些细节:什么是根对象?GC 机制的触发时机?
  • “天神之眼”计算平台的算力设计(预计500-1000 TOPS)
  • 马上评|这种“维权”已经不算薅羊毛,涉嫌犯罪了
  • 遭“特朗普关税”冲击,韩国今年经济增长预期“腰斩”降至0.8%
  • 2025财政观察|长三角“三公”经费普降,钱要用在刀刃上
  • “11+2”复式票,宝山购彩者领走大乐透1170万头奖
  • 福建厦门市副市长、市公安局局长陈育煌出任吉林省公安厅厅长
  • 反制美国钢铝关税!印度拟对美国部分商品征收关税