用两个栈模拟一个队列
栈是先进后出的原理,即FILO,队列是先进先出的原理,即FIFO
#include <iostream> using namespace std; #define MAXSIZE 256 typedef struct stack { int top; int stack[MAXSIZE]; }Stack; void initQueue(Stack *s) //初始化队列 { s->top=0; } void enQueue(Stack *s,int elem) //入队 { if(s->top<MAXSIZE) { s->top++; //队首元素从以1开始 s->stack[s->top]=elem; } } void deQueue(Stack *s1,Stack *s2) //模拟出队 { if(s1->top>0) { while(s1->top>0) { s2->stack[++s2->top]=s1->stack[s1->top--]; } cout<<"deQueue:"<<s2->stack[s2->top]<<endl; s2->top--; if(s2->top>0) { while(s2->top>0) { s1->stack[++s1->top]=s2->stack[s2->top--]; } } } else { cout<<"queue is empty!"; } } int main() { Stack s1,s2; int array[]={1,2,3,4,5,6,7,8,9}; int i; cout<<"init the queue:"<<endl; //初始化队列 initQueue(&s1); initQueue(&s2); cout<<"enQueue:"<<endl; //入队操作 for(i=0;i<9;i++) { enQueue(&s1,array[i]); } cout<<"deQueue:"<<endl; //出队 deQueue(&s1,&s2); cout<<"deQueue:"<<endl; deQueue(&s1,&s2); cout<<"deQueue:"<<endl; deQueue(&s1,&s2); return 0; }
运行截图: