[数据结构]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;
}
相关推荐
Pniubi6 分钟前
怎么排查慢SQL,怎么解决?
java·数据库·sql
Decay__4 小时前
VMware 安装 SQL Server 双节点 AlwaysOn 可用性组教程 —— WSFC、AG 与侦听器完整部署(系列核心篇)
运维·数据库·sql·mysql·架构
测试界的小码农4 小时前
【Linux 命令实战(06):Linux 文件权限管理,掌握 chmod、chown、chgrp】
linux·运维·服务器
茶栀(*´I`*)5 小时前
SQL 性能分析:从慢查询日志到执行计划的完整定位方法
数据库·sql
艺杯羹5 小时前
1Panel 装好后 ufw 仍是 inactive:一次服务器安全盲区复盘
服务器·数据库·安全·网络安全·系统架构·实战·1panel
一条破秋裤6 小时前
【1114】【并发控制】【笔记】
linux
code2cat6 小时前
【随笔】MCP工具重试:任务已经创建,响应丢了怎么办
数据库·mcp
2035去旅行7 小时前
ADB的底层原理
linux·adb·嵌入式·arm·soc
武子康7 小时前
单卡 A6000 跑 Qwen-Drive:怎样留下可比较的第一条基线?
linux·人工智能·深度学习
女神下凡8 小时前
芯参谋(107):杰理AC_中科蓝讯_开发指南
linux·服务器·网络·单片机·嵌入式硬件