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

【数据结构】:栈的实现

在这里插入图片描述

1 栈

1.1栈的概念及结构

栈:一种特殊的线性表,其只允许在固定的一端进行插入和删除元素操作。进行数据插入和删除操作的一端称为栈顶,另一端称为栈底。栈中的数据元素遵守后进先出LIFO(Last In First Out)的原则
压栈:栈的插入操作叫做进栈/压栈/入栈,入数据在栈顶
出栈:栈的删除操作叫做出栈。出数据也在栈顶
在这里插入图片描述
在这里插入图片描述

1.2栈的实现

栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上插入数据的
代价比较小
在这里插入图片描述
在这里插入图片描述
全部代码如下 特别注意 栈的特征是后进先出

#include"Stack.h"
void STInit(ST* ps)
{assert(ps);ps->a = NULL;ps->capacity = 0;ps->top = 0;
}
void STDestroy(ST* ps)
{assert(ps);free(ps->a);ps->a = NULL;ps->top = 0;ps->capacity = 0;
}
void STPush(ST* ps, SLDataType x)
{assert(ps);if (ps->top == ps->capacity){int NewCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;SLDataType* tmp = (SLDataType*)realloc(ps->a, sizeof(SLDataType) * NewCapacity);if (tmp == NULL){perror("realloc fail");exit(-1);}ps->a = tmp;ps->capacity = NewCapacity;}
}
void STPop(ST* ps)
{assert(ps);assert(ps->top > 0);ps->top--;
}
int STSize(ST* ps)
{assert(ps);return ps->top;
}
bool STEmpty(ST* ps)
{assert(ps);return ps->top == NULL;
}
#pragma once
#include<stdio.h>
#include<assert.h>
#include<stdlib.h>
#include<stdbool.h>
//#define N 10
typedef int SLDataType;
typedef struct Stack
{SLDataType* a;int top;int capacity;
}ST;
void STInit(ST* ps);
void STDestroy(ST* ps);
void SLPush(ST* ps, SLDataType x);
void STPop(ST* ps);
int STSize(ST* ps);
bool STEmpty(ST* ps);
http://www.lryc.cn/news/195070.html

相关文章:

  • 微前端一:技术选型
  • FPGA project : flash_continue_write
  • 论文阅读:Rethinking Range View Representation for LiDAR Segmentation
  • 本地配置免费的https咋做?
  • 微信小程序框架---详细教程
  • 【LeetCode刷题(数组and排序)】:存在重复元素
  • 半导体产业链解析:晶圆厂、无晶圆厂与代工厂的比较与作用
  • Apipost一键压测已支持导入CSV文件
  • RabbitMQ的5种模式——再探RabbitMQ的模式,简单、工作,发布订阅(广播),路由、主题 页面分析
  • 初识华为云数据库GaussDB for openGauss
  • 深圳寄包裹到德国
  • 系统架构师备考倒计时22天(每日知识点)Redis篇
  • 现有库存(on-hand inventory),库存水平(inventory level),库存位置(inventory position)
  • 智慧空开让用电更安全、管理更智能——电脑APP远程控制开合闸
  • PyTorch 中张量运算广播
  • Blender:使用立方体制作动漫头像
  • 【ppt技巧】ppt里的图片如何提取出来?
  • Python学习基础笔记七十三——调试程序
  • BOSHIDA DC电源模块关于电容器的电解液位置
  • 如何实现 Es 全文检索、高亮文本略缩处理(封装工具接口极致解耦)
  • C++多线程编程(第四章 案例1,C++11和C++17 多核并行计算样例)
  • 获取远程仓库的信息和远程分支的信息
  • QT学习day1
  • unity面试八股文 - 框架设计与资源管理
  • 智能网关IOT 2050采集应用
  • iOS代码混淆-从入门到放弃
  • 基于Eigen的位姿转换
  • Jmeter之Bean shell使用详解
  • TCP/IP(八)TCP的连接管理(五)四次握手
  • MyBatis-Plus主键生成策略[MyBatis-Plus系列] - 第491篇