#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));
}
共享栈的实现与测试
最新推荐文章于 2024-10-05 15:32:05 发布