[数据结构]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;
}
相关推荐
db_murphy2 小时前
Oracle数据块8KB、OS默认认块管理4KB,是否需调整大小为一致?
linux
mCell5 小时前
从删库到跑路?这50个Linux命令能保你职业生涯
linux·windows·macos
杰克逊的日记5 小时前
GPU运维常见问题处理
linux·运维·gpu
誰能久伴不乏6 小时前
Linux系统调用概述与实现:深入浅出的解析
linux·运维·服务器
程序员学习随笔6 小时前
Linux进程深度解析(2):fork/exec写时拷贝性能优化与exit资源回收机制(进程创建和销毁)
linux·运维·服务器
mmoyula6 小时前
【RK3568 PWM 子系统(SG90)驱动开发详解】
android·linux·驱动开发
-SGlow-7 小时前
MySQL相关概念和易错知识点(2)(表结构的操作、数据类型、约束)
linux·运维·服务器·数据库·mysql
爱装代码的小瓶子7 小时前
数据结构之队列(C语言)
c语言·开发语言·数据结构
代码改变世界ctw7 小时前
Linux内核设计与实现 - 第14章 块I/O层
linux·运维·服务器
明月5668 小时前
Oracle 误删数据恢复
数据库·oracle