[数据结构]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;
}
相关推荐
不知几秋2 小时前
数字取证-内存取证(volatility)
java·linux·前端
欧先生^_^5 小时前
Linux内核可配置的参数
linux·服务器·数据库
问道飞鱼5 小时前
【数据库知识】Mysql进阶-高可用MHA(Master High Availability)方案
数据库·mysql·adb·高可用·mha
tiging5 小时前
centos7.x下,使用宝塔进行主从复制的原理和实践
数据库·mysql·adb·主从复制
海尔辛5 小时前
学习黑客5 分钟读懂Linux Permissions 101
linux·学习·安全
wangcheng86995 小时前
Oracle常用函数-日期时间类型
数据库·sql·oracle
zizisuo5 小时前
面试篇:Spring Security
网络·数据库·安全
一只fish6 小时前
MySQL 8.0 OCP 1Z0-908 题目解析(2)
数据库·mysql
StarRocks_labs6 小时前
从InfluxDB到StarRocks:Grab实现Spark监控平台10倍性能提升
大数据·数据库·starrocks·分布式·spark·iris·物化视图
搞不懂语言的程序员6 小时前
Redis的Pipeline和Lua脚本适用场景是什么?使用时需要注意什么?
数据库·redis·lua