232.Implement Queue Using Stack
示例:
MyQueue queue = new MyQueue();
queue.push(1);
queue.push(2);
queue.peek(); // 返回 1
queue.pop(); // 返回 1
queue.empty(); // 返回 falseclass MyQueue {
private:
stack<int> mq1;
stack<int> mq2;
public:
/** Initialize your data structure here. */
MyQueue() {
}
/** Push element x to the back of queue. */
void push(int x) {
if(mq2.empty())
mq2.push(x);
else
{
while(!mq2.empty())
{
mq1.push(mq2.top());
mq2.pop();
}
mq2.push(x);
while(!mq1.empty())
{
mq2.push(mq1.top());
mq1.pop();
}
}
}
/** Removes the element from in front of queue and returns that element. */
int pop() {
int t=mq2.top();
mq2.pop();
return t;
}
/** Get the front element. */
int peek() {
return mq2.top();
}
/** Returns whether the queue is empty. */
bool empty() {
return mq2.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();
*/Last updated