顺序栈存储还是很方便的,不过它有一个致命的缺点,就是必须事先确定数组存储空间大小,万一不够用了,就需要编程手段来扩展数组的容量。但如果我们有两个相同类型的栈,我们为他们各自开辟了数组空间,这时,我们完全可以用一个数组存储两个栈。
栈的抽象数据类型
ADT 栈(stack)
Data
同线性表。元素具有相同的类型,相邻元素具有前驱和后继关系
Operation
InitStack(*S):初始化操作,建立一个空栈S
ClearStack(*S):将栈清空
StackEmpty(S):若栈为空,返回true,否则返回false
GetTop(*S,*e):若栈存在且非空,用e返回S的栈顶元素
Push(*S,e,stackNumber):若栈存在,插入新元素e到栈stacknumber中并成为栈顶元素,stacknumber为选择第几个栈
Pop(*S,*e,stackNumber):删除栈stackNumber中栈顶元素,并用e返回其值
StackTraverse(S):遍历栈中所有元素
StackLength(S):返回栈S的元素个数
endADT
代码如下:(编译软件VS2017)
#include<stdio.h>
#include<string.h>
#include<stdlib.h>
#include<io.h>
#define OK 1
#define ERROR 0
#define TRUE 1
#define FALSE 0
#define MAXSIZE 30
typedef int Status;
typedef int SElempType;//SElemType根据实际情况而定
typedef struct
{
SElempType data[MAXSIZE];
int top1;//栈1栈顶指针
int top2;//栈2栈顶指针
}SqDoubleStack;
//输出元素C
Status visit(SElempType c)
{
printf("%d ", c);
return OK;
}
//构造一个空栈
Status InitStack(SqDoubleStack *S)
{
S->top1 = -1;
S->top2 = MAXSIZE;
return OK;
}
//把S置为空栈
Status ClearStack(SqDoubleStack *S)
{
S->top1 = -1;
S->top2 = MAXSIZE;
return OK;
}
//若栈为空返回TRUE,否则返回FALSE
Status StackEmpty(SqDoubleStack S)
{
if (S.top1 == -1 && S.top2 == MAXSIZE)
{
return TRUE;
}
else
return FALSE;
}
//返回S元素的个数,即栈的长度
Status StackLength(SqDoubleStack S)
{
return (S.top1 + 1) + (MAXSIZE - S.top2-1);
}
//插入元素e为新的栈顶元素
Status Push(SqDoubleStack *S, SElempType e, int stackNUmber)
{
if (S->top1 + 1 == S->top2)//栈满
return ERROR;
if (stackNUmber == 1)//栈1有元素进栈
S->data[++S->top1] = e;//若是栈1则先top+1后给数组元素赋值
else if (stackNUmber == 2)//栈2有元素进栈
S->data[--S->top2] = e;//若是栈2则先top2-1后给数组元素赋值
return OK;
}
//若栈不为空,则删除S的栈顶元素,用e返回其值,并返回OK;否则返回ERROR
Status Pop(SqDoubleStack *S, SElempType *e, int stackNUmber)
{
if (stackNUmber == 1)
{
if (S->top1 == -1)
return ERROR;//说明1已经是空栈,溢出
*e = S->data[S->top1--];//将栈1的栈顶元素出栈
}
else if (stackNUmber == 2)
{
if (S->top2 == MAXSIZE)
return ERROR;
*e = S->data[S->top2++];
}
return OK;
}
//输出栈
Status 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");
return OK;
}
int main()
{
int j;
SqDoubleStack s;
int e;
if (InitStack(&s) == OK)
{
for (j = 1; j <= 5; j++)
Push(&s, j, 1);
for (j = MAXSIZE; j >= MAXSIZE; 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));
system("pause");
return 0;
}
运行结果截图: