classMyQueue{public:
stack<int> stIn;
stack<int> stOut;MyQueue(){}// 入栈无返回,有参数voidpush(int x){
stIn.push(x);}// 出栈有返回,返回出栈的元素intpop(){//只有当stOut为空时,再从stIn中导入全部数if(stOut.empty()){//倒入数据,直到stIn为空while(!stIn.empty()){
stOut.push(stIn.top());
stIn.pop();}}//出栈的有元素,可以出栈,临时保存栈顶int front = stOut.top();
stOut.pop();return front;}intpeek(){int res =this->pop();//直接使用已有的pop函数
stOut.push(res);// 因为pop函数弹出了元素res,所以添加回去return res;}boolempty(){return stOut.empty()&& stIn.empty();}};/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue* obj = new MyQueue();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->peek();
* bool param_4 = obj->empty();
*/
2. leetcode 225 用队列实现栈
//两个队列classMyStack{public:
queue<int> queue1;
queue<int> queue2;/** Initialize your data structure here. */MyStack(){}/** Push element x onto stack. */voidpush(int x){
queue2.push(x);while(!queue1.empty()){
queue2.push(queue1.front());
queue1.pop();}swap(queue1, queue2);}/** Removes the element on top of the stack and returns that element. */intpop(){int r = queue1.front();
queue1.pop();return r;}/** Get the top element. */inttop(){int r = queue1.front();return r;}/** Returns whether the stack is empty. */boolempty(){return queue1.empty();}};// 一个队列// 一个队列在模拟栈弹出元素的时候只要将队列头部的元素(除了最后一个元素外)// 重新添加到队列尾部,此时弹出的元素就是栈的顺序classMyStack{public:
queue<int> q;/** Initialize your data structure here. */MyStack(){}/** Push element x onto stack. */voidpush(int x){int n = q.size();
q.push(x);for(int i =0; i < n; i++){
q.push(q.front());
q.pop();}}/** Removes the element on top of the stack and returns that element. */intpop(){int r = q.front();
q.pop();return r;}/** Get the top element. */inttop(){int r = q.front();return r;}/** Returns whether the stack is empty. */boolempty(){return q.empty();}};classMyStack{public:
queue<int> que;MyStack(){}voidpush(int x){
que.push(x);}intpop(){int size = que.size();
size--;while(size--){
que.push(que.front());
que.pop();}int res = que.front();
que.pop();return res;}inttop(){return que.back();}boolempty(){return que.empty();}};/**
* Your MyStack object will be instantiated and called as such:
* MyStack* obj = new MyStack();
* obj->push(x);
* int param_2 = obj->pop();
* int param_3 = obj->top();
* bool param_4 = obj->empty();
*/