数据结构之共享栈

//共享栈
#include<stdio.h>

#define MaxSize 5
#define ElemType int

typedef struct {
ElemType data[MaxSize];
int top1;
int top2;
}SqStack;

//初始化
void initStack(SqStack *S)
{
S->top1=-1;
S->top2=MaxSize;
}
//判断是否是空栈
int StackEmpty(SqStack *S)
{
if(S->top1==-1&&S->top2==MaxSize)return 1;
else{return 0;}
}

//判断是否是满栈
int Stackfull(SqStack *S)
{
if((S->top1)-(S->top2)==-1)return 1;
else{return 0;}
}

//数据压入,先判断是否满
int Push1(SqStack *S,ElemType target)
{
if(Stackfull(S))
{
printf("栈满\n");
return 0;
}

S->data[++S->top1]=target;
return 1;
}
int Push2(SqStack *S,ElemType target)
{
if(Stackfull(S))
{
printf("栈满\n");
return 0;
}

S->data[--S->top2]=target;
return 1;
}


//数据弹出,先判断是否空
int Pop1(SqStack *S,ElemType *target)
{
if(S->top1==-1)
{
printf("空栈\n");
return 0;
}
else{
*target=S->data[S->top1];
S->top1--;
return 1;
}
}
int Pop2(SqStack *S,ElemType *target)
{
if(S->top2==MaxSize)
{
printf("空栈\n");
return 0;
}
else{
*target=S->data[S->top2];
S->top2++;
return 1;
}
}

//读栈顶元素,利用指针将数据传出,返回的是是否读取成功
int read_top1(SqStack *S,ElemType *target)
{
if(S->top1==-1)
{
printf("空栈\n");
return 0;
}
else{
*target=S->data[S->top1];
return 1;
}
}
int read_top2(SqStack *S,ElemType *target)
{
if(S->top2==MaxSize)
{
printf("空栈\n");
return 0;
}
else{
*target=S->data[S->top2];
return 1;
}
}


int main()
{
SqStack S;
initStack(&S);
int cot=5;
int tmp;
while(cot--)
{
Push1(&S,cot);
if(read_top1(&S,&tmp))
{
printf("top数值:%d\n",tmp);
}

}
if(Stackfull(&S))printf("满\n");
//Push1(&S,6);

return 0;
}

 

比较奇特的栈,因为它为了空间的有效利用选择了两个栈共用一个数组空间,由此会有两个栈顶属性 top1 top2

posted @ 2022-07-15 23:09  天天掉头发  阅读(61)  评论(0编辑  收藏  举报
返回顶端