思路:
- 一个队列是 FIFO 的,但一个栈是 LIFO 的。这就意味着新j进入的元素必须得放在栈底。为了实现这个目的,我们首先需要把s1的所有元素移到s2中,然后把s2中的元素弹出,再把弹出的元素压入s1
- 这里借几张图片
- 入队:
- 出队
- s1的栈顶元素就是队首元素 直接弹s1
class MyQueue
{
public:
/** Initialize your data structure here. */
stack<int> stack1; //push栈实现队列push操作
stack<int> stack2; //pop栈实现队列pop操作
MyQueue()
{
}
/** Push element x to the back of queue. */
void push(int x)
{
//直接将元素push进push栈stack1
stack1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop()
{
//将stack1所有元素push进stack2,则stack2栈顶元素为队头元素
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
//取队头元素,并将队头元素pop
int s = stack2.top();
stack2.pop();
//将stack2中元素重新放回stack1中
while(!stack2.empty())
{
stack1.push(stack2.top());
stack2.pop();
}
return s;
}
/** Get the front element. */
int peek()
{
while(!stack1.empty())
{
stack2.push(stack1.top());
stack1.pop();
}
int s = stack2.top();
while(!stack2.empty())
{
stack1.push(stack2.top());
stack2.pop();
}
return s;
}
/** Returns whether the queue is empty. */
bool empty()
{
return stack1.empty() && stack2.empty();
}
};