题目描述
请用栈实现一个队列,支持如下四种操作
样例
class MyQueue {
public:
stack<int> myStack;
stack<int> p;
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
myStack.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int len=myStack.size();
for(int i=0;i<len-1;i++){
p.push(myStack.top());
myStack.pop();
}
int target=myStack.top();
myStack.pop();
while(!p.empty()){
myStack.push(p.top());
p.pop();
}
return target;
}
/** Get the front element. */
int peek() {
int len=myStack.size();
for(int i=0;i<len-1;i++){
p.push(myStack.top());
myStack.pop();
}
int target=myStack.top();
for(int i=0;i<len-1;i++){
myStack.push(p.top());
p.pop();
}
return target;
}
/** Returns whether the queue is empty. */
bool empty() {
return myStack.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();
*/