如果对你有帮助记得点赞 >_< 祝天天开心
//共享栈 一个从上向下存储 一个从下向上存储
#include <stdio.h>
#include <stdbool.h>
#define MaxSize 10
typedef int ElemType;
typedef struct
{
ElemType data[MaxSize];
int htop;
int ltop;
}ShareStack;
//初始化共享栈
bool InitStack(ShareStack *s)
{
s->ltop=-1;
s->htop=MaxSize;
return true;
}
//获取共享栈长度
int GetStackLength(ShareStack s)
{
return ((s.ltop+1)+(MaxSize-s.htop));
}
//判断共享栈是否为空 为空返回true否则返回false
bool isEmpty(ShareStack s)
{
if(s.ltop==-1&&s.htop==MaxSize)
{
return true;
}
return false;
}
//判断共享栈是否为满
bool isFull(ShareStack s)
{
if(s.ltop+1==s.htop)
{
return true;
}
return false;
}
//清空共享栈
bool ClearShareStack(ShareStack *s)
{
s->htop=MaxSize;
s->ltop=-1;
return true;
}
//入栈 flag表示数据元素加哪个栈
bool Push(ShareStack *s,char flag,ElemType e)
{
if(!(flag=='H'||flag=='L'))
{
printf("不知道要入哪个栈");
return false;
}
if(isFull(*s))
{
printf("栈满,加不了");
return false;
}
if(flag=='L')
{
s->ltop++;
s->data[s->ltop]=e;
}else if(flag=='H')
{
s->htop--;
s->data[s->htop]=e;
}
return true;
}
//查看栈顶元素
ElemType GetTop(ShareStack s,char flag)
{
if(!(flag=='H'||flag=='L'))
{
printf("不知道看哪个栈\n");
return false;
}
if(isEmpty(s))
{
printf("栈空,无元素可看\n");
}
if(flag=='H'&&s.htop!=MaxSize)
{
return s.data[s.htop];
}
if(flag=='L'&&s.ltop!=-1)
{
return s.data[s.ltop];
}
return false;
}
//打印共享栈
void PrintfShareStack(ShareStack s)
{
if(isEmpty(s))
{
printf("空栈,没得打印\n");
return;
}
while(s.ltop>-1)
{
printf("%d\t",s.data[s.ltop]);
s.ltop--;
}
while(s.htop<MaxSize)
{
printf("%d\t",s.data[s.htop]);
s.htop++;
}
printf("\n");
}
int main(void)
{
ShareStack s;
InitStack(&s);
for(int i=0;i<6;i++)
{
if(i%2==0)
{
Push(&s,'L', i);
}
else
{
Push(&s,'H', i);
}
}
PrintfShareStack(s);
// ClearShareStack(&s);
PrintfShareStack(s);
int len=GetStackLength(s);
printf("%d\n",len);
int ans=GetTop(s, 'H');
printf("%d\n",ans);
return 0;
}
>_<