两个栈实现一个队列,如何实现?
顾名思义就是用两个栈来实现队列的先进先出这个特性,栈本身的特性是后进先出。
所以一个栈肯定是无法实现的,所以要用到两个栈,主栈用来进出数据,另外一个栈辅助实现队列。实现过程就是当数据要出队时,将主栈的数据依次出到另外一个栈然后再出队。
栈的结构体:
typedef struct Sqstack
{
int elem[STACK_LEN];
int top;
}Sqstack,*Pstack;
实现代码:
//初始化栈
void InitStack(Pstack ps)
{
assert(ps != NULL);
ps->top = 0;
}
//判满
static bool IsFull(Pstack ps)
{
assert(ps != NULL);
if((ps->top) >= STACK_LEN)
{
return true;
}
return false;
}
//入栈
bool Push(Pstack ps,int val)
{
assert(ps != NULL);
if(IsFull(ps))
{
return false;
}
ps->elem[ps->top++] = val;
return true;
}
//判空
static bool IsEmpty(Pstack ps)
{
assert(ps != NULL);
if(ps->top == 0)
return true;
return false;
}
//出栈
bool Pop(Pstack ps,int *rtv)
{
assert(ps != NULL);
if(IsEmpty(ps))
{
return false;
}
if(rtv != NULL)
{
ps->top--;
*rtv = ps->elem [ps->top];//出栈的值保存在rtv中 出栈会删掉占中原有的值
}
return true;
}
//入队
void EnterQueue(Pstack ps1,int val)
{
Push(ps1,val);//在这里入队及入栈,直接调用入栈函数
}
//出队
int PopQueue(Pstack ps1,Pstack ps2)//ps1为主栈,ps2为辅助栈
{
int tmp = 0;
if(IsEmpty(ps2))//ps2为空时,ps1的数据出栈然后入ps2的栈
{
while(!IsEmpty(ps1))
{
Pop(ps1,&tmp);
Push(ps2,tmp);
}
}
int tmp2 = 0;
if(!IsEmpty(ps2))//ps2不为空出栈,及实现出队
{
Pop(ps2,&tmp2);
}
return tmp2;
}
//打印
void Show(Pstack ps2)
{
assert(ps2 != NULL);
for(int i=0;i<ps2->top;i++)
{
printf("%d ",ps2->elem[i]);
}
printf("\n");
}