栈的基本操作

  栈,一种特殊的线性表,只允许在固定的 一端进行插入和删除操作,栈中的数据遵循后进先出原则。可以用数组和链表来表示栈。

(1)如果使用链式栈,如果用尾作栈顶,尾插尾删,要设计成双向链表,否则删除数据效率低。如果用头作栈顶,头插头删,可以设计成单链表。

(2)综合这两种,如果非要选一种,数组栈稍微好一点。

1,定义栈

typedef struct Stack {
	 STDatatype* a; //使用动态的数组
	 int top; //栈顶元素下一个元素的下标
	 int capacity;//栈的容量
}ST;

 2,栈的基本操作


void StackInit(ST* ps);//初始化
void StackDestroy(ST* ps);//销毁栈
void StackPush(ST* ps, STDatatype x);//入栈
void StackPop(ST* ps);//出栈
bool StackEmpty(ST* ps);//判断栈是否为空
int StackSize(ST* ps);//栈中元素的个数
STDatatype StackTop(ST* ps);//栈顶元素

实现 

#pragma once
#include"stack.h"
void StackInit(ST* ps)
{
	assert(ps);//指向结构体的指针不能为空
	ps->a = NULL;
	ps->capacity = ps->top = 0;

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

}
void StackPush(ST* ps, STDatatype x)
{
	assert(ps);
	if (ps->top == ps->capacity)//如果栈已满,则需要扩容,一般扩容为原来的1.5或2倍;
	{
		int newcapacity = ps->capacity == 0 ? 4 : ps->capacity * 2;//刚开始没有容量时,就随便定一个容量,有容量就扩容为原来的2倍;
		STDatatype *temp = realloc(ps->a, sizeof(STDatatype)*newcapacity);//刚开始栈为空时,使用realloc与使用malloc一样;
		if (temp == NULL)
		{
			printf("realloc fail\n");
			exit(-1);
		}
		ps->a = temp;
		ps->capacity = newcapacity;
	}

		ps->a[ps->top] = x;
		ps->top++;
	
}
void StackPop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));//栈不为空继续
	ps->top--;
}
bool StackEmpty(ST* ps)
{
	assert(ps);
	if (ps->top == 0)
		return true;
	else
		return false;
}
int StackSize(ST* ps)
{
	assert(ps);
	return ps->top;
}
STDatatype StackTop(ST* ps)
{
	assert(ps);
	assert(!StackEmpty(ps));
	return ps->a[ps->top - 1];
}

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值