数据结构————顺序栈

本文介绍了顺序栈的基本概念,它是一种后进先出的线性表。详细阐述了顺序栈的初始化、销毁、压栈、出栈、查看栈顶元素、获取栈的元素个数以及判断栈是否为空的操作。同时,给出了相应的C语言实现代码。
摘要由CSDN通过智能技术生成

顺序栈

1. 顺序栈定义

栈(Stack):是只允许在一端进行插入或删除的线性表。首先栈是一种线性表,但限定这种线性表只能在某一端进行插入和删除操作。


栈又称为后进先出(Last In First Out)的线性表。

在这里插入图片描述

typedef struct Stack
{
  STDataType* a;
  int top;          //有效数据个数(栈顶位置)
  int capacity;     //容量
}ST;

2. 顺序栈初始化

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

3. 顺序栈销毁

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

4. 顺序栈插入(压栈)

void StackPush(ST* ps,STDataType x){
	assert(ps);
	if(ps->capacity == ps->top){      //判断容量是否足够,如果不够则增容
		int newcapacity = ps->capacity ==0?4:(ps->capacity)*2; 
		STDataType* temp = (STDataType*)realloc(ps->a,sizeof(STDataType)*newcapacity);//扩容
		if(temp == NULL){
			printf("realloc fault");	
			exit(-1);		
		}
		ps->a = temp;				 //把扩容地址传给a
		ps->capacity = newcapacity;	 
	}
	ps->a[ps->top] = x;				 //插入元素x
	ps->top++;

};

5. 顺序栈删除(出栈)

void StackPop(ST* ps){
	assert(ps);
	assert(StackEmpty(ps) != 1);
	ps->top--;
};

6. 栈顶元素查看

STDataType StackTop(ST* ps){
	assert(ps);
	assert(StackEmpty(ps) != 1);

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

7. 查看栈的元素个数

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

8.判断栈是否为空 为空返回1

int StackEmpty(ST* ps){
	assert(ps);
	if(ps->top == 0){
		return 1;
	}
	else
		return 0;
};
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值