[数据结构]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;
}
相关推荐
无限进步_4 分钟前
【C语言】队列(Queue)数据结构的实现与分析
c语言·开发语言·数据结构·c++·算法·链表·visual studio
l1t4 分钟前
解决PostgreSQL中找不到uniq函数的错误
数据库·postgresql
爱吃番茄鼠骗5 分钟前
Linux操作系统———守护进程
linux
墨白曦煜12 分钟前
深入剖析 Redis 客户端:Sentinel 模式下的“寻址”与“感知”艺术
数据库·redis·sentinel
Nerd Nirvana13 分钟前
IPv6组播在DLMS协议中的应用——基础知识掌握
linux·运维·服务器·网络·网络协议·ipv6·dlms协议
水上冰石14 分钟前
harbor使用https之证书生成
服务器·数据库·https
福尔摩斯张16 分钟前
TCP/IP网络编程深度解析:从Socket基础到高性能服务器构建(超详细)
linux·运维·服务器·开发语言·网络·网络协议·tcp/ip
Sleepy MargulisItG17 分钟前
【Linux网络编程】传输层协议:TCP
linux·网络·tcp/ip
卡布叻_星星18 分钟前
Docker之Windows与Linux不同架构部署理解
linux·windows·docker
重生之我是Java开发战士18 分钟前
【算法日记】排序算法:原理、实现、性能与应用
数据结构·算法·排序算法