定义
用一个数组来实现两个栈,这称为共享栈。
示意图:
声明共享栈:
typedef struct
{
ElemType data[MaxSize];
int top1,top2; //栈指针
} DStack;
基本运算
设计共享栈基本运算算法四要素:
1.栈空的条件:栈1空为top1==-1,栈2空为top2==MaxSize;
2.栈满条件:top1==top2-1;
3.元素进栈操作:进栈1操作为top1++,data[top1]=e。进栈2操作为top2–,data[top2]=e;
4.元素出栈操作:出栈1操作为e=data[top1],top1–。出栈2操作为e=data[top2],top2++.
同时在实现共享栈基本运算算法时需要增加一个形参i,指出对哪个栈进行操作。
初始化栈
void InitStack(DStack *&s)
{
s=(DStack *)malloc(sizeof(DStack));
s->top1=-1; // 栈1栈顶指针初始化为-1
s->top2=MaxSize; //栈2栈顶指针初始化为MaxSize
}
销毁栈
void DestroyStack(DStack *&s)
{
free(s);
}
判断栈是否为空
bool StackEmpty(DStack *s,int i)
{
if(i==1)
return(s->top1==-1);
if(i==2)
return(s->top2==MaxSize);
}
进栈操作
bool Push(DStack *&s,ElemType e,int i)
{
if (s->top1==s->top2) //栈满的情况,即栈上溢出
return false;
if(i==1)
{
s->top1++;
s->data[s->top1]=e;
}
if(i==2)
{
s->top2--;
s->data[s->top2]=e;
}
return true;
}
出栈操作
bool Pop(DStack *&s,ElemType &e,int i)
{
if(i==1)
{
if (s->top1==-1) //栈为空的情况,即栈下溢出
return false;
e=s->data[s->top1];
s->top1--;
}
if(i==2)
{
if(s->top2==MaxSize)
return false;
e=s->data[s->top2];
s->top2++;
}
return true;
}
取栈顶元素
bool GetTop(DStack *s,ElemType &e,int i)
{
if (s->top1==s->top2) //栈为空的情况,即栈下溢出
return false;
if(i==1)
{
e=s->data[s->top1];
}
if(i==2)
{
e=s->data[s->top2];
}
return true;
}
完整代码
#include <stdio.h>
#include <malloc.h>
#define MaxSize 100
typedef char ElemType;
typedef struct
{
ElemType data[MaxSize];
int top1,top2; //栈指针
} DStack; //共享栈类型
void InitStack(DStack *&s)
{
s=(DStack *)malloc(sizeof(DStack));
s->top1=-1;
s->top2=MaxSize;
}
void DestroyStack(DStack *&s)
{
free(s);
}
bool StackEmpty(DStack *s,int i)
{
if(i==1)
return(s->top1==-1);
if(i==2)
return(s->top2==MaxSize);
}
bool Push(DStack *&s,ElemType e,int i)
{
if (s->top1==s->top2) //栈满的情况,即栈上溢出
return false;
if(i==1)
{
s->top1++;
s->data[s->top1]=e;
return true;
}
if(i==2)
{
s->top2--;
s->data[s->top2]=e;
return true;
}
}
bool Pop(DStack *&s,ElemType &e,int i)
{
if(i==1)
{
if (s->top1==-1) //栈为空的情况,即栈下溢出
return false;
e=s->data[s->top1];
s->top1--;
return true;
}
if(i==2)
{
if(s->top2==MaxSize)
return false;
e=s->data[s->top2];
s->top2++;
return true;
}
}
bool GetTop(DStack *s,ElemType &e,int i)
{
if (s->top1==s->top2) //栈为空的情况,即栈下溢出
return false;
if(i==1)
{
e=s->data[s->top1];
}
if(i==2)
{
e=s->data[s->top2];
}
return true;
}
int main()
{
DStack *s;
ElemType e;
InitStack(s); //初始化栈
Push(s,1,1);
Push(s,2,1);
Push(s,3,1); //依次对栈1进行进栈操作
Push(s,4,2);
Push(s,5,2);
Push(s,6,2); //依次对栈2进行进栈操作
printf("栈1元素为:\n");
Pop(s,e,1);
printf("%d ",e);
Pop(s,e,1);
printf("%d ",e);
Pop(s,e,1); //依次对栈1进行出栈操作
printf("%d\n",e);
printf("栈2元素为:\n");
Pop(s,e,2);
printf("%d ",e);
Pop(s,e,2);
printf("%d ",e);
Pop(s,e,2); //依次对栈2进行出栈操作
printf("%d\n",e);
return 0;
}
参考资料:
李春葆《数据结构教程》(第五版)