```#include <stdio.h>
#include <stdlib.h>
#define MaxSize 4
typedef int ElemType;
typedef struct {
ElemType data[MaxSize];
int top1;
int top2;
}sharedStack;
void InitStack(sharedStack &S);
bool StackEmpty(sharedStack S,int whichStack);
bool Push(sharedStack &S,ElemType x,int whichStack);
bool Pop(sharedStack &S,ElemType &x,int whichStack);
bool GetTop(sharedStack &S,ElemType &x,int whichStack);
bool DestroyStack(sharedStack &S);
void Display(sharedStack &S,int whichStack);
void InitStack(sharedStack &S){
S.top1=-1;
S.top2=MaxSize;
}
int main(){
sharedStack *S=(sharedStack*)malloc(sizeof(sharedStack));
InitStack(*S);
StackEmpty(*S,1);
StackEmpty(*S,2);
Push(*S,1,1);
Push(*S,2,1);
Push(*S,3,2);
Push(*S,4,2);
Push(*S,5,2);
Display(*S,1);
Display(*S,2);
DestroyStack(*S);
Display(*S,1);
Display(*S,2);
}
bool StackEmpty(sharedStack S,int whichStack){
switch(whichStack){
case 1:
if(S.top1!=-1)
printf("第一个栈非空\n");
else{
printf("第一个栈为空\n");
}
return false;
case 2:
if(S.top2!=MaxSize)
printf("第二个栈非空\n");
else
printf("第二个栈为空\n");
return false;
}
}
bool Push(sharedStack &S,ElemType x,int whichStack){
switch(whichStack){
case 1:
if(S.top1+1==S.top2){
printf("栈存储空间已满\n");
return false;
}
else{
S.data[++S.top1]=x;
printf("第一个栈插入成功\n");
return true;
}
case 2:
if(S.top2-1==S.top1)
{
printf("存储空间已满\n");
return false;
}
else{
S.data[--S.top2]=x;
printf("第二个栈插入成功\n");
return true;
}
}
}
bool Pop(sharedStack &S,ElemType &x,int whichStack){
switch(whichStack){
case 1:
if(S.top1==-1){
printf("第一个栈为空\n");
return false;
}else{
x=S.data[S.top1--];
printf("第一个栈取出元素%d\n",x);
return true;
}
case 2:
if(S.top2==MaxSize){
printf("第二个栈为空\n");
return false;
}else{
x=S.data[S.top2++];
printf("第二个栈取出元素%d\n",x);
return true;
}
}
}
bool GetTop(sharedStack &S,ElemType &x,int whichStack){
switch(whichStack){
case 1:
if(S.top1==-1){
printf("第一个栈为空\n");
return false;
}else{
x=S.data[S.top1];
printf("第一个栈栈顶元素%d\n",x);
return true;
}
case 2:
if(S.top2==MaxSize){
printf("第二个栈为空\n");
return false;
}else{
x=S.data[S.top2];
printf("第二个栈栈顶元素%d\n",x);
return true;
}
}
}
bool DestroyStack(sharedStack &S){
S.top1=-1;
S.top2=MaxSize;
free(S.data);
}
void Display(sharedStack &S,int whichStack){
if(whichStack==1){
printf("打印第一个栈的元素\n");
int t=S.top1;
while(t!=-1){
printf("栈1元素:%d\n",S.data[t--]);
}
printf("打印第一个栈的元素结束\n");
}
else{
printf("打印第二个栈的元素\n");
int t=S.top2;
while(t!=MaxSize){
printf("栈2元素:%d\n",S.data[t++]);
}
printf("打印第二个栈的元素结束\n");
}
}
共享栈的实现(基于C语言)
最新推荐文章于 2024-03-01 20:01:14 发布