Queues are implemented using two stacks

Analysis: also use two last in first out, simulate first in first out. Pop () = pop() = pop() = pop() = pop() = pop()

#include <Stdio.h> #define MAX 1000 void Push(int *stackA,int &topA,int data) { stackA[++topA]=data; } int Pop(int *stackA,int &topA,int *stackB,int &topB) { int ret=-1; if(topA==topB&&topA==-1) { printf("the stack is empty!" ); return NULL; } if(topB>=0) { ret=stackB[topB--]; }else if(topB<0) { for(; topA! = 1) { stackB[++topB]=stackA[topA--]; } ret=stackB[topB--]; } return ret; } void TwoStack() { int stackA[MAX]; int stackB[MAX]; int topA,topB; topA=topB=-1; Push(stackA,topA,500); Push(stackA,topA,100); int ret1=Pop(stackA,topA,stackB,topB); printf("%d\n",ret1); int ret2=Pop(stackA,topA,stackB,topB); printf("%d\n",ret2); } int main() { TwoStack(); }Copy the code