[数据结构]5. 栈-Stack

发布于:2025-05-15 ⋅ 阅读:(9) ⋅ 点赞:(0)

1. 介绍

栈(stack) 是一种遵循先入后出逻辑的线性数据结构。顶部称为“栈顶”,底部称为“栈底”。把元素添加到栈顶的操作叫作“入栈”,删除栈顶元素的操作叫作“出栈”。
请添加图片描述

2. 栈的实现

2.1 基于链表的实现

请添加图片描述请添加图片描述请添加图片描述

2.2 基于数组的实现

请添加图片描述请添加图片描述
请添加图片描述

3. 栈操作

Create

typedef int STDataType;
typedef struct Stack
{
	STDataType* a;
	int top;
	int capacity;
}ST;

Initilizate

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

void STDestory(ST* pst) {
	assert(pst);
	free(pst->a);
	pst->top = pst->capacity = 0;
}

Push

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

void STPop(ST* pst) {
	assert(pst);
	assert(!STEmpty(pst));
	pst->top--;
}

Top

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

bool STEmpty(ST* pst) {
	assert(pst);
	return pst->top == 0;
}

Size

int STSize(ST* pst) {
	assert(pst);
	return pst->top;
}