数据结构入门——04栈

1.栈

栈是限制在一端进行插入操作和删除操作的线性表(俗称堆栈)

允许进行操作的一端称为“栈顶”,另一固定端称为“栈底”,当栈中没有元素时称为“空栈”。

栈的特点 :后进先出LIFO(Last In First Out)。

栈的实现一般可以使用数组或者链表实现,相对而言数组的结构实现更优一些。因为数组在尾上
插入数据的代价比较小。

  • 数组实现栈

  • 链表实现栈

2.栈的数组实现

2.1数组栈的表示

//定长数组栈
typedef int STDataType;
#define N 10
typedef struct Stack
{
    STDataType _a[N];
    int _top; // 栈顶
}Stack;


//动态增长数组栈   //和顺序表类似
typedef int STDataType;
typedef struct Stack
{
    STDataType* _a;
    int _top; // 栈顶
    int _capacity; // 容量
}Stack;

2.2 初始化栈

void StackInit(ST* ps)
{
	assert(ps);
	ps->a = NULL;
	ps->top = 0;
	ps->capacity = 0;
}

2.3 入栈

void StackPush(ST* ps, STDataType x)
{
	assert(ps);
	// 满了扩容
	if (ps->top == ps->capacity)
	{
		int newCapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;
		ps->a = (STDataType*)realloc(ps->a, newCapacity* sizeof(STDataType));
		if (ps->a == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}

		ps->capacity = newCapacity;
	}

	ps->a[ps->top] = x;
	ps->top++;
}

2.4 出栈

void StackPop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);
	--ps->top;
}

2.5 获取栈顶元素

STDataType StackTop(ST* ps)
{
	assert(ps);
	assert(ps->top > 0);

	return ps->a[ps->top - 1];
}

2.6 获取栈中有效元素个数

int StackSize(ST* ps)
{
	assert(ps);
	return ps->top;
}

2.7 检测栈是否为空,如果为空返回非零结果,如果不为空返回0

bool StackEmpty(ST* ps)
{
	assert(ps);

	/*if (ps->top > 0)
	{
		return false;
	}
	else
	{
		return true;
	}*/
	return ps->top == 0;
}

2.8 销毁栈

void StackDestory(ST* ps)
{
	assert(ps);
	free(ps->a);
	ps->a = NULL;
	ps->capacity = ps->top = 0;
}

  • 5
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值