[数据结构]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;
}
相关推荐
夏鹏今天学习了吗42 分钟前
【LeetCode热题100(31/100)】K 个一组翻转链表
算法·leetcode·链表
瑶总迷弟1 小时前
在 CentOS 7.6 上安装 Oracle WebLogic Server 12c 详细教程
linux·oracle·centos
156082072191 小时前
在飞腾D2000/8平台下ubuntu内核添加WX1860和WX1820的驱动
linux·ubuntu
心灵宝贝1 小时前
如何在 CentOS 7 上安装 bzip2-libs-1.0.6-13.el7.x86_64.rpm 文件
linux·运维·centos
云心雨禅1 小时前
WordPress提速指南:Memcached+Super Static Cache+CDN缓存网站内容
linux·服务器·数据库·缓存·memcached
Pluchon1 小时前
硅基计划4.0 算法 字符串
java·数据结构·学习·算法
麦格芬2302 小时前
LeetCode 416 分割等和子集
数据结构·算法
鹿鸣天涯2 小时前
Kali Linux 2025.3 正式发布:更贴近前沿的安全平台
linux·运维·安全
Mr.wangh2 小时前
Redis主从复制
java·数据库·redis
穿背心的程序猿2 小时前
推荐一款集成AI功能的数据库管理工具
数据库