主要思路是:
对于push操作,将数据插入非空队列中,如果两个队列都为空,则插入任意一个队列中;
对于pop操作,将数据从非空的队列中迁移到空队列中去,并且输出非空队列中的最后一个元素。
/* 用两个队列来模拟栈的push和pop操作 */ void queueStack(){queue<int> q1;queue<int> q2;int n; //操作的次数int value;scanf("%d",&n);char* operation = (char*)malloc(sizeof(char)*4);for(int i=0;i<n;i++){scanf("%s",operation);if(strcmp(operation,"PUSH")==0){ //插入非空队列中,如果两个队列都为空,则插入任意一个scanf("%d",&value);if(q1.size()!=0){q1.push(value);}else if(q2.size()!=0){q2.push(value);}else{q1.push(value);}}else if(strcmp(operation,"POP")==0){ //将非空队列中的元素迁移到空队列中去,最后一个元素就是栈顶的元素if(q1.size()>0 && q2.size()==0){while(q1.size()>1){q2.push(q1.front());q1.pop();}printf("%d\n",q1.front());q1.pop();}else if(q1.size()==0 && q2.size()>0){while(q2.size()>1){q1.push(q2.front());q2.pop();}printf("%d\n",q2.front());q2.pop();}else if(q1.size()==0 && q2.size()==0){printf("-1\n");}else{printf("error\n");}}} }