[数据结构]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;
}
相关推荐
叠叠乐1 分钟前
redmi k90 pro max 强解BL,刷海外rom, 并刷入sukisu ultra
linux
初夏睡觉16 分钟前
数据结构学习之~二叉堆 (P3378 【模版】堆)
数据结构·c++·学习
AI人工智能+电脑小能手18 分钟前
【大白话说Java面试题 第84题】【Mysql篇】第14题:为什么用 InnoDB 存储引擎的表建议用整型的自增主键?
java·开发语言·数据库·mysql·面试
张彦峰ZYF29 分钟前
检索增强生成(RAG)系统的基础:全面深入矢量数据库
数据库·大模型·rag
云泽8081 小时前
笔试算法 - 链表篇(一):移除、反转、合并、回文判断全解析
数据结构·c++·算法·链表
也曾看到过繁星1 小时前
数据结构-复杂度
数据结构
菜菜的顾清寒1 小时前
HOT力扣100(43)二叉树-翻转二叉树
数据结构·算法·leetcode
xiaoye-duck1 小时前
《Linux系统编程》Linux 进程间通信之管道基础解析:从匿名管道原理到基于管道的进程池实现
linux
z200509301 小时前
【Linux学习】Linux中的进程程序替换
linux·服务器·学习