使用栈实现队列的下列操作:
push(x) – 将一个元素放入队列的尾部。 pop() – 从队列首部移除元素。 peek() – 返回队列首部的元素。 empty() – 返回队列是否为空。
来源:力扣(LeetCode) 链接:https://leetcode-cn.com/problems/implement-queue-using-stacks 著作权归领扣网络所有。商业转载请联系官方授权,非商业转载请注明出处。
class MyQueue {
stack<int> inSTK;
stack<int> outSTK;
public:
/** Initialize your data structure here. */
MyQueue() { }
/** Push element x to the back of queue. */
void push(int x) {
inSTK.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop()
{
if(!outSTK.empty())
{
int tp = outSTK.top();
outSTK.pop();
return tp;
}
else
{
while(!inSTK.empty())
{
outSTK.push(inSTK.top());
inSTK.pop();
}
int tp = outSTK.top();
outSTK.pop();
return tp;
}
}
/** Get the front element. */
int peek() {
if(!outSTK.empty())
return outSTK.top();
else
{
while(!inSTK.empty())
{
outSTK.push(inSTK.top());
inSTK.pop();
}
return outSTK.top();
}
}
/** Returns whether the queue is empty. */
bool empty() {
return inSTK.empty() && outSTK.empty();
}
};