[数据结构]5. 栈-Stack

栈-Stack

  • [1. 介绍](#1. 介绍)
  • [2. 栈的实现](#2. 栈的实现)
    • [2.1 基于链表的实现](#2.1 基于链表的实现)
    • [2.2 基于数组的实现](#2.2 基于数组的实现)
  • [3. 栈操作](#3. 栈操作)

1. 介绍

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

2. 栈的实现

2.1 基于链表的实现

2.2 基于数组的实现


3. 栈操作

Create

c 复制代码
typedef int STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;
	int capacity;
}ST;

Initilizate

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

Destory

c 复制代码
void STDestory(ST* pst) {
	assert(pst);
	free(pst->a);
	pst->top = pst->capacity = 0;
}

Push

c 复制代码
void STPush(ST* pst, STDataType x) {
	// Enpend capacity
	if (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

c 复制代码
void STPop(ST* pst) {
	assert(pst);
	assert(!STEmpty(pst));
	pst->top--;
}

Top

c 复制代码
STDataType STTop(ST* pst) {
	assert(pst);
	assert(!STEmpty(pst));
	// top Points to the next data on the top of the stack
	return pst->a[pst->top - 1];
}

Empty

c 复制代码
bool STEmpty(ST* pst) {
	assert(pst);
	return pst->top == 0;
}

Size

c 复制代码
int STSize(ST* pst) {
	assert(pst);
	return pst->top;
}
相关推荐
小米里的大麦30 分钟前
022 基础 IO —— 文件
linux
Xの哲學35 分钟前
Perf使用详解
linux·网络·网络协议·算法·架构
门前灯35 分钟前
Linux系统之iprconfig 命令详解
linux·运维·服务器·iprconfig
奶黄小甜包40 分钟前
C语言零基础第18讲:自定义类型—结构体
c语言·数据结构·笔记·学习
想不明白的过度思考者44 分钟前
数据结构(排序篇)——七大排序算法奇幻之旅:从扑克牌到百亿数据的魔法整理术
数据结构·算法·排序算法
手把手入门1 小时前
★CentOS:MySQL数据备份
数据库·mysql·adb
一支闲人1 小时前
C语言相关简单数据结构:双向链表
c语言·数据结构·链表·基础知识·适用于新手小白
tb_first1 小时前
k8sday09
linux·云原生·容器·kubernetes
忧郁的橙子.1 小时前
三、k8s 1.29 之 安装2
linux·运维·服务器
姜不吃葱1 小时前
【力扣热题100】双指针—— 接雨水
数据结构·算法·leetcode·力扣热题100