栈--顺序栈--共享栈

//顺序栈
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#define MaxSize 10
typedef int ElemType;
typedef struct {
	ElemType data[MaxSize];
	int top;
}SqStack;
bool InitStack(SqStack& S)
{
	S.top = -1;//指向当前栈顶元素若=0则指向下一个存储位置
	return true;
}
bool StackEmpty(SqStack S)
{
	return(S.top == -1);
}
bool Push(SqStack& S, ElemType x)
{
	if (S.top == MaxSize - 1)
		return false;
	S.data[++S.top] = x;
	return true;
}
bool Pop(SqStack& S, ElemType& x)
{
	if (StackEmpty(S))
		return false;
	x = S.data[S.top--];
	return true;
}
bool GetTop(SqStack S, ElemType& x)
{
	if (StackEmpty(S))
		return false;
	x = S.data[S.top];
	return true;
}
bool DestroyStack(SqStack& S)
{
	S.top = -1;//顺序栈位于栈区函数结束自动回收
	return true;
}
int main()
{
	SqStack S;
	ElemType e;
	InitStack(S);
	Push(S, 3);
	Push(S, 5);
	Push(S, 7);
	Pop(S, e);
	printf("Pop e=%3d\n", e);
	GetTop(S, e);
	printf("Get e=%3d\n", e);
	Pop(S, e);
	printf("Pop e=%3d\n", e);
	GetTop(S, e);
	printf("Get e=%3d\n", e);
	DestroyStack(S);
	Pop(S, e);
	printf("Pop e=%3d\n", e);
	if (Pop(S, e))
		printf("Pop e=%3d\n", e);
	else
		printf("Pop fail\n");
	return 0;
}



//共享栈--简易
#define _CRT_SECURE_NO_WARNINGS
#include<stdio.h>
#define MaxSize 10
typedef int ElemType;
typedef struct {
	ElemType data[MaxSize];
	int top0, top1;
}SqShStack;
void InitSqShStack(SqShStack& S)
{
	S.top0 = -1;
	S.top1 = MaxSize;
}
//应该分开判断左边栈右边栈是否为空此处简写
bool SqShStackEmpty(SqShStack S)
{
	if (S.top0 == -1 && S.top1 == MaxSize)
		return true;
	else return false;
}
bool SqShStackfull(SqShStack S)
{
	return (S.top0 + 1 == S.top1);
}
bool Push(SqShStack& S, ElemType e1, ElemType e2)
{
	if (SqShStackfull(S)) return false;
	S.data[++S.top0] = e1;
	S.data[--S.top1] = e2;
	return true;
}
bool GetTop(SqShStack S, ElemType& e1, ElemType& e2)
{
	if (SqShStackEmpty(S)) return false;
	e1 = S.data[S.top0];
	e2 = S.data[S.top1];
	return true;
}
bool Pop(SqShStack& S, ElemType& e1, ElemType& e2)
{
	if (SqShStackEmpty(S)) return false;
	e1 = S.data[S.top0--];
	e2 = S.data[S.top1++];
	return true;
}
bool DestroyStack(SqShStack& S)
{
	S.top0 = -1;
	S.top1 = MaxSize;
	return true;
}
int main()
{
	SqShStack S;
	InitSqShStack(S);
	ElemType e1,e2;
	Push(S, 3,-3);
	Push(S, 5,-5);
	Push(S, 7,-7);
	Pop(S, e1,e2);
	GetTop(S, e1, e2);
	Pop(S, e1, e2);
	GetTop(S, e1, e2);
	DestroyStack(S); 
	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值