C语言实现——共享顺序栈

结构体中需要两个栈顶指针
一个从下至上存放
一个从上至下存放


#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#include<stdlib.h>
#include<stdbool.h>

#define maxsize 10

typedef struct {
	int data[maxsize];
	int top0;			//0号栈栈顶指针
	int top1;			//1号栈栈顶指针
}ShStack;

//初始化栈
void InitStack(ShStack &s)
{
	//初始化栈顶指针
	s.top0=-1;			//从下至上存放
	s.top1=maxsize;		//从上至下存放		
}

//判空操作
bool emptystack(ShStack s)
{
	if(s.top0==-1 && s.top1==maxsize)
		return true;
	else
		return false;
}

//判满操作
bool fullstack(ShStack s)
{
	if(s.top0==s.top1-1)
		return true;
	else 
		return false;
}

//往0号栈里存入元素
bool push0stack(ShStack &s,int x)
{
	if(s.top0==s.top1-1)		//栈满
		return false;
	s.top0++;
	s.data[s.top0]=x;
	return true;
}

//往1号栈里存入元素
bool push1stack(ShStack &s, int x)
{
	if(s.top0==s.top1-1)		//栈满
		return false;
	s.top1--;
	s.data[s.top1]=x;
	return true;
}

//从0号栈中弹出元素
bool pop0stack(ShStack &s, int &e)
{
	if(s.top0==-1)				//0号栈空
		return false;
	e=s.data[s.top0];
	s.top0--;
	return true;
}

//从1号栈中弹出元素
bool pop1stack(ShStack &s, int &e)
{	
	if(s.top1==maxsize)			//1号栈空
		return false;	
	e=s.data[s.top1];
	s.top1++;
	return true;
}

//读取0号栈顶的元素
bool gettop0(ShStack s)
{
	if(s.top0==-1)		//0号栈空
		return false;
	printf("%d\n",s.data[s.top0]);
	return true;
}

//读取1号栈栈顶元素
bool gettop1(ShStack s)
{
	if(s.top1==maxsize)	//1号栈空
		return false;
	printf("%d\n",s.data[s.top1]);
	return true;
}

int main()
{
	ShStack s;
	int e=0;
	InitStack(s);
	if (emptystack(s))
		printf("栈空\n");
	push0stack(s,999);
	gettop0(s);
	push1stack(s,99);
	gettop1(s);

	pop0stack(s,e);
	printf("%d\n",e);

	pop1stack(s,e);
	printf("%d\n",e);

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值