Implement the following operations of a stack using queues.
- push(x) -- Push element x onto stack.
- pop() -- Removes the element on top of the stack.
- top() -- Get the top element.
- empty() -- Return whether the stack is empty.
此时队列2中有元素。是可运行的容器。队列1是空,备用容器,所以我们须要两个表示符,代表两个队列,表示此队列是否是当前可操作的容器。简单来讲,就是用两个队列的操作(push()。pop(),empty())来实现栈的各种操作。
#include<iostream> #include<queue> using namespace std; queue<int> qu1; queue<int> qu2; bool qu1_use=1; bool qu2_use=0; void push(int x); void pop() ; int top() ; bool empty() ; void main() { push(1); push(2); push(3); push(4); int i=5; while(i) { if(!empty()) { cout<<top()<<endl; pop(); } i--; } } void push(int x) { if(qu1_use==1) { qu1.push(x); } else qu2.push(x); } void pop() { if(qu1.empty()&&qu2.empty()) exit(0); if(qu1_use==1&&!qu1.empty()) { while(qu1.size()>1) { qu2.push(qu1.front()); qu1.pop(); } qu1.pop(); qu1_use=0; qu2_use=1; return; } if(qu2_use==1&&!qu2.empty()) { while(qu2.size()>1) { qu1.push(qu2.front()); qu2.pop(); } qu2.pop(); qu1_use=1; qu2_use=0; return; } return; } int top() { if(qu1_use==1&&!qu1.empty()) { return qu1.back(); } if(qu2_use==1&&!qu2.empty()) { return qu2.back(); } //if(qu1.empty()&&qu2.empty()) exit(0); } bool empty() { if((qu1_use==1&&qu1.empty())||(qu2_use==1&&qu2.empty())) { cout<<"empty!"<<endl; return true; } else return false; }
运行上面代码得到结果为: