思路
用两个栈st_in和st_out实现队列,st_in负责实现“入队”操作,st_out负责实现“出队”操作;
队列操作
(2)push():执行st_in.push();
(3)pop():如果st_out不为空则执行st_out.pop();如果为空,则将st_in中的元素全部入栈到st_out中;
(4)peek():同上类似;
(5)empty():如果两个栈都为空,则队列为空。
class MyQueue {
public:
/** Initialize your data structure here. */
stack<int> st_in;
stack<int> st_out;
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
st_in.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
if(st_out.empty()){
while(st_in.size()){
st_out.push(st_in.top());
st_in.pop();
}
}
int el = st_out.top();
st_out.pop();
return el;
}
/** Get the front element. */
int peek() {
if(st_out.empty()){
while(st_in.size()){
st_out.push(st_in.top());
st_in.pop();
}
}
return st_out.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return st_out.empty() && st_in.empty();
}
};
/**
* Your MyQueue object will be instantiated and called as such:
* MyQueue obj = MyQueue();
* obj.push(x);
* int param_2 = obj.pop();
* int param_3 = obj.peek();
* bool param_4 = obj.empty();
*/