#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define StackSize 100
//DataType为元素的数据类型,stack用于存储共享栈中的数据元素的数组
//top[0]和top[1]为栈顶数组下标
typedef char DataType;
typedef struct
{
DataType stack[StackSize];
int top[2];
}SSeqStack;
//初始化栈
void SStackInit(SSeqStack *S)
{
S->top[0]=0;
S->top[1]=StackSize-1;
}
//取栈顶元素.flag为1表示取左端元素,flag为2表示取右端元素
int GetTopS(SSeqStack S, DataType *e,int flag)
{
if(flag==1)
{
if(S.top[0]<=0)
{
printf("左栈已经空!\n");
return 0;
}
else
{
*e=S.stack[S.top[0]-1];
return 1;
}
}
else if(flag==2)
{
if(S.top[1]>=StackSize-1)
{
printf("右栈已经空!\n");
return 0;
}
else
{
*e=S.stack[S.top[1]+1];
return 1;
}
}
else
{
printf("不正确的参数!\n");
return 0;
}
}
//将元素入栈
int PushSStack(SSeqStack *S, DataType e, int flag)
{
if(flag==1)
{
if(S->top[0]>=S->top[1])//栈满的条件是相等还是大于?认为均可以
{
printf("栈已经满!\n");
return 0;
}
else
{
S->stack[S->top[0]]=e;
S->top[0]++;
return 1;
}
}
else if(flag==2)
{
if(S->top[0]>=S->top[1] )
{
printf("栈已经满!\n");
return 0;
}
else
{
S->stack[S->top[1]]=e;
S->top[1]--;
return 1;
}
}
else
{
return 0;
}
}
//将栈顶元素出栈
int PopSStack(SSeqStack *S, DataType *e,int flag)
{
if(flag==1)
{
if(S->top[0]==0)
{
printf("左栈已经空!\n");
return 0;
}
else
{
S->top[0]--;
*e=S->stack[S->top[0]];
return 1;
}
}
else if(flag==2)
{
if(S->top[1]==StackSize-1)
{
printf("右栈已经空!\n");
return 0;
}
else
{
S->top[1]++;
*e=S->stack[S->top[1]];
return 1;
}
}
else
{
return 0;
}
}
//清空栈
void ClearSStack(SSeqStack *S)
{
S->top[0]=0;
S->top[1]=StackSize-1;
}
int main()
{
DataType a[]={'a','b','c','d','e','f'};
DataType b[]={'p','w','x','y','z'};
SSeqStack B;
DataType e1, e2;
int i=0;
SStackInit(&B);
for(i=0;i<sizeof(a)/sizeof(DataType);i++)
{
PushSStack(&B,a[i],1);
}
for(i=0;i<sizeof(b)/sizeof(DataType);i++)
{
PushSStack(&B,b[i],2);
}
for(i=0;i<sizeof(a)/sizeof(DataType);i++)
{
PopSStack(&B,&e1,1);
printf("%c ",e1);
}
printf("\n******************\n");
for(i=0;i<sizeof(b)/sizeof(DataType);i++)
{
PopSStack(&B,&e2,2);
printf("%c ",e2);
}
return 0;
}
复制代码
共享栈基本操作
最新推荐文章于 2022-11-07 21:36:24 发布