题目描述:使用栈实现队列的入队,出队,返回队头元素,判断队列是否为空
解题思路:之前写过一篇使用栈实现队列的博文,但是仅仅实现了队列的出队和入队操作,这篇博客作为其补充,思路与其完全一致。另有一篇使用队列实现栈的博文,可共同学习。
- 使用STL中的stack创建两个栈,s1 和 s2,s1 负责入栈,s2 负责出栈;
- 队列入队:使用 STL 中的 stack 会动态分配内存,因此不必担心栈满的情况,所以入队时,直接将元素入 s1 栈即可。
- 队列出队:出队时需要 s2 出栈,因此要判定 s2 是否为空;若 s2 为空,则将 s1 中元素一一出栈进入 s2 栈中,此时 s2 已不为空;那么队列出队只需将 s2 出栈即可。当然,如果 s1 和 s2 均为空,则出队失败;
- 队列头元素:头元素应该是 s2 的栈顶元素,因此要判定 s2 是否为空;若 s2 为空,则将 s1 中元素一一出栈进入 s2 栈中,此时 s2 已不为空;那么 s2 的栈顶元素即为队列的头元素,返回即可;当然,若 s1 和 s2 同时为空,返回0;
- 队列判空:若 s1 和 s2 同时为空,则队列空。
C++实现如下:
class MyQueue {
public:
/** Initialize your data structure here. */
MyQueue() {}
stack<int> s1;
stack<int> s2;
/** Push element x to the back of queue. */
void push(int x)
{
s1.push(x);
}
/** Removes the element from in front of queue and returns that element. */
int pop()
{
if(s1.empty() && s2.empty())
return 0;
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
int ret = s2.top();
s2.pop();
return ret;
}
/** Get the front element. */
int peek()
{
if(s1.empty() && s2.empty())
return 0;
if(s2.empty())
{
while(!s1.empty())
{
s2.push(s1.top());
s1.pop();
}
}
return s2.top();
}
/** Returns whether the queue is empty. */
bool empty()
{
return s1.empty() && s2.empty();
}
};