题目链接:https://leetcode-cn.com/problems/implement-queue-using-stacks/
题目如下:
class MyQueue {
public:
stack<int> stk1;
stack<int> stk2;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
//将元素压入堆栈stk1
stk1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
//将元素放到stk2,拿到最先放入stk1的元素,并移除,再放回stk1
int num;
while(!stk1.empty()){
num=stk1.top();
stk1.pop();
stk2.push(num);
}
num=stk2.top();
stk2.pop();
int num1;
while(!stk2.empty()){
num1=stk2.top();
stk2.pop();
stk1.push(num1);
}
return num;
}
/** Get the front element. */
int peek() {
//将元素依次放到stk2,拿到最后一个出栈的元素,再还原回去
int num;
while(!stk1.empty()){
num=stk1.top();
stk1.pop();
stk2.push(num);
}
int num1;
while(!stk2.empty()){
num1=stk2.top();
stk2.pop();
stk1.push(num1);
}
return num;
}
/** Returns whether the queue is empty. */
bool empty() {
return stk1.empty()&&stk2.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();
*/