共享栈的实现与测试

#include"stdio.h"
#include"def.h"

void visit(ElemType e) {
	printf("%d\t", e);
}

//初始化
void InitStack(SqDoubleStack &S) {
	S.top1 = -1;
	S.top2 = MaxSize;
}


//置空
void ClearStack(SqDoubleStack& S) {
	S.top1 = -1;
	S.top2 = MaxSize;
}

//判断栈是否为空
bool StackEmpty(SqDoubleStack S) {
	if (S.top1 == -1 && S.top2 == MaxSize)
		return true;
	else
		return false;
}

bool StackFull(SqDoubleStack S) {
	if (S.top2-S.top1 == 1)
		return false;
	else
		return true;
}

//获取栈长
int StackLength(SqDoubleStack S) {
	return (S.top1 + 1) + (MaxSize - S.top2);
}

//入栈
bool Push(SqDoubleStack &S, ElemType e, int stackNumber) {
	if (S.top1 + 1 == S.top2)
		return false;
	if (stackNumber == 1)
		S.data[++S.top1] = e;
	else if (stackNumber == 2)
		S.data[--S.top2] = e;
	else
		return false;
	return true;
}

//出栈
bool Pop(SqDoubleStack& S, ElemType &e, int stackNumber) {//e为引用,需要将参数传会e,否则就是局部变量了
	if (stackNumber == -1) {
		if (S.top1 == -1)
			return false;
		e = S.data[S.top1--];
	}
	else if (stackNumber == 2) {
		if (S.top2 == MaxSize)
			return false;
		e = S.data[S.top2++];
	}
	return true;
}

//输出
void StackTraverse(SqDoubleStack S) {
	int i=0;
	while (i <= S.top1) {
		visit(S.data[i++]);
	}
	i = S.top2;
	while (i < MaxSize) {
		visit(S.data[i++]);
	}
	printf("\n");
}

int main() {
	int j;
	SqDoubleStack S;
	ElemType e=0;
	InitStack(S);
	for (j = 1; j <= 5; j++) {
		Push(S, j,1);

	}
	for (j = MaxSize; j >= MaxSize - 3; j--) {
		Push(S, j, 2);
	}

	printf("栈中元素:\n");
	StackTraverse(S); //1       2       3       4       5       17      18      19      20
	printf("%d\n",StackLength(S));
	Pop(S, e, 2);
	printf("%d\n",e);
	//StackEmpty(S);
	printf("1表示空%d\n", StackEmpty(S));
	for (j = 6; j <= MaxSize - 3;j++)
		Push(S,j,1);
	StackTraverse(S);
	printf("0表示满%d\n", StackFull(S));
	ClearStack(S);
	printf("1表示空%d\n", StackEmpty(S));
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值