#include<iostream>
using namespace std;
const int MAXSIZE = 20;
typedef int SElemType;
/* 两栈共享空间结构 */
typedef struct
{
SElemType data[MAXSIZE];
int top1; /* 栈 1 栈顶指针 */
int top2; /* 栈 2 栈顶指针 */
}SqDoubleStack;
void visit(SElemType c)
{
cout << c;
}
void InitStack(SqDoubleStack &S)
{
S.top1 = -1;
S.top2 = MAXSIZE;
}
#define ClearStack InitStack
bool StackEmpty(SqDoubleStack S)
{
if (S.top1 == -1 && S.top2 == MAXSIZE)
return true;
else
return false;
}
int StackLength(SqDoubleStack S)
{
return (S.top1 + 1) + (MAXSIZE - 1 - S.top2);
}
bool Push(SqDoubleStack &S, SElemType e, int stackNumber)
{
if (S.top1 + 1 == S.top2) /* 栈已满,不能再 push 新元素了 */
return false;
if (stackNumber == 1) /* 栈 1 有元素进栈 */
S.data[++S.top1] = e; /* 若是栈 1 则先 top1+1 后给数组元素赋值。 */
else if (stackNumber == 2) /* 栈 2 有元素进栈 */
S.data[--S.top2] = e; /* 若是栈 2 则先 top2-1 后给数组元素赋值。 */
return true;
}
bool Pop(SqDoubleStack &S, SElemType &e, int stackNumber)
{
if (stackNumber == 1)
{
if (S.top1 == -1)
return false; /* 说明栈 1 已经是空栈,溢出 */
e = S.data[S.top1--]; /* 将栈 1 的栈顶元素出栈 */
return true;
}
else if (stackNumber == 2)
{
if (S.top2 == MAXSIZE)
return false; /* 说明栈 2 已经是空栈,溢出 */
e = S.data[S.top2++]; /* 将栈 2 的栈顶元素出栈 */
return true;
}
else
return false;
}
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++]);
}
cout << endl;
}
void main()
{
int j;
SqDoubleStack s;
int e;
InitStack(s);
for (j = 1; j <= 5; j++)
Push(s, j, 1);
for (j = MAXSIZE; j >= MAXSIZE - 2; j--)
Push(s, j, 2);
printf("栈中元素依次为:");
StackTraverse(s);
printf("当前栈中元素有:%d \n", StackLength(s));
Pop(s, e, 2);
printf("弹出的栈顶元素 e=%d\n", e);
printf("栈空否:%d(1:空 0:否)\n", StackEmpty(s));
for (j = 6; j <= MAXSIZE - 2; j++)
Push(s, j, 1);
printf("栈中元素依次为:");
StackTraverse(s);
printf("栈满否:%d(1:否 0:满)\n", Push(s, 100, 1));
ClearStack(s);
printf("清空栈后,栈空否:%d(1:空 0:否)\n", StackEmpty(s));
}数据结构之共享栈(顺序存储)—改编《大话数据结构》
最新推荐文章于 2024-10-14 22:23:55 发布
本文介绍了一种使用共享数组实现的两个栈的数据结构,并提供了初始化、判断空栈、获取栈长度、压栈、出栈及遍历等基本操作的C++实现。通过具体实例展示了如何操作双栈。
2819

被折叠的 条评论
为什么被折叠?



