写了用栈模拟队的实现后,自然也探索一下用队模拟栈的实现,其中如有bug或者可优化的地方,还请多多指教。。
在这里,队的那些基本实现函数就不哆嗦了。
用队实现栈,就是说,需要用队的特性-->先进先出 ,模拟栈的特性-->后进先出。。
看看代码吧。。
#include <stdio.h>
#include "queue_to_stack.h"
/队转栈---》两个队,其中一个只负责中转,帮助另一个实现“后进先出
bool push_queue_to_stack(node *q1,ELEMTYPE val)
{
push_list_queue(q1,val);
return false;
}
static int length_queue(node *q)
{
int tmp;
int count=0;
if (q==NULL )
{
return false;
}
while(!is_empty(q))
{
pop_list_queue(q,&tmp);
count++;
}
return count;
}
int pop_queue_to_stack(node *q1,node *q2)
{
if (is_empty(q1))
{
printf("栈空");
return true;
}
while(!is_empty(q1))
{
int tmp=0;
int buff=0;
while(length_queue(q1)!=1)
{
pop_list_queue(q1,&buff);
push_list_queue(q2,buff);
}
pop_list_queue(q1,&tmp);
printf("%d\n",tmp);
while(is_empty(q2)!=0)
{
pop_list_queue(q2,&buff);
push_list_queue(q1,buff);
}
}
return 0;
}
int main()
{
node s1;
node s2;
init_list_queue(&s1);
push_list_queue(&s1,3);
push_list_queue(&s1,8);
push_list_queue(&s1,6);
init_list_queue(&s2);
push_queue_to_stack(&s1,2);
int tmp=pop_queue_to_stack(&s1,&s2);
printf("%d\n",tmp);
return 0;
}