两个栈实现一个队列,C语言实现,队列可伸缩,容纳任意数目的元素。

时间:2024-07-08 15:05:26

一、思路:1、创建两个空栈A和B;2、A栈作为队列的入口,B栈作为队列的出口;3、入队列操作:即是入栈A;4、出队列操作:若栈B为空,则将A栈内容出栈并压人B栈,再出      B栈;不为空就直接出栈;

二、代码:

  1、头文件:stack_to_queue.h:封装了:队列、栈的数据结构和各种操作的函数。

 #ifndef STACK_TO_QUEUE_H
#define STACK_TO_QUEUE_H #include<stdio.h>
#include<stdlib.h> #define ALLOC_SIZE 512
#define ElemType int typedef struct sqstack
{
ElemType *top; //栈顶指针
ElemType *base; //栈底指针
int stack_size; //栈目前能存储的元素数目
}SqStack; //顺序栈 typedef struct sqqueue
{
SqStack front; //队列头,出口,
SqStack rear; //队列尾,入口
}SqQueue; /*栈的初始化函数*/
void InitStack(SqStack *s)
{
if((s->top=(ElemType*)malloc(ALLOC_SIZE*sizeof(ElemType)))==NULL)
{
printf("stack malloc error\n");
exit();
}
s->base=s->top;
s->stack_size=ALLOC_SIZE;
} /*出栈函数,栈为空时返回0,成功出栈时返回1*/
int pop_stack(SqStack *s,ElemType *data)
{
if(s->top!=s->base)
{
s->top--;
*data=*s->top;
return ;
}
else //返回值为0,表示栈为空
{
return ;
}
} /*入栈函数*/
void push_stack(SqStack *s,ElemType data)
{
if((s->top-s->base)>=s->stack_size)
{
if((s->base=(ElemType *)realloc(s->base,(s->stack_size+ALLOC_SIZE)*sizeof(ElemType)))==NULL)
{
printf("stack realloc error\n");
exit();
}
else
{
s->top=s->base+s->stack_size;
s->stack_size+=ALLOC_SIZE;
}
}
*(s->top)=data;
s->top++;
} /*队列初始化函数*/
void InitQueue(SqQueue *q)
{
SqStack A,B; InitStack(&A);
InitStack(&B);
q->front=B; //将栈B作为队列的出口
q->rear=A; //将栈A作为队列的入口
} /*入队列函数*/
void push_queue(SqQueue *q,ElemType data)
{
push_stack(&q->rear,data);
} /*出队列函数,队列为空时返回0,成功出队列返回1*/
int pop_queue(SqQueue *q,ElemType *data)
{
if((pop_stack(&q->front,data))==) //如果作为出口的栈为空,就将入口栈的内容压入
{
while((pop_stack(&q->rear,data))!=)
{
push_stack(&q->front,*data);
}
}
else //否则,返回1
{
return ;
}
if((pop_stack(&q->front,data))==) //如果将入口栈的内容压人后还为空,说明此时队列为空
{
return ;
}
else
{
return ;
}
}
#endif

2、主函数:main.c:只为测试用,通过for循环让1000个数0-999入队列,再打印。

 #include<stdio.h>
#include"stack_to_queue.h" int main()
{
SqQueue q;
int i,data; InitQueue(&q);
for(i=;i<;i++)
{
push_queue(&q,i);
}
while((pop_queue(&q,&data))!=)
{
printf("%d ",data);
} return ;
}

之前写的时候犯了一个错误,在stack_to_queue.h中的62行,使用realloc函数重新分配内存后,要将top指针也指向新的位置,我漏掉了这一步,导致出错,检查了很久,最后的解决过程在这:http://q.cnblogs.com/q/54337/