您的位置:首页 > 编程语言 > C语言/C++

利用两个队列实现一个栈(C++版)

2015-11-26 00:50 786 查看
题目:

利用两个队列实现一个栈的功能,完成pop() push() top() empty()等功能。

push(x) -- Push element x into stack.
pop() -- Removes the element on top of the stack.
top() -- Get the top element.
empty() -- Return whether the stack is empty

思路:

两个队列q1, q2。不管是插入还是弹出,保证总有一个队列为空。那么:

队列入栈:将元素插入空队列,同时将非空队列的元素依次插入到空队列。此时之前的非空队列变为空队列,空队列变为非空队列。

队列出栈:将非空队列的队首弹出即可。

举例说明:

执行下述操作:先将1 2 3入栈,接着3出栈,然后4入栈。两个队列元素的变化情况如下:

1. 初始:q1 q2为空 将1压入q1。此时q1非空 q2为空。

2. 元素2入栈 q2为空 压入。之前q1非空,将1弹出压入q2。此时q1为空 q2为2 1。

3.
元素3入栈 q1为空 压入。之前q2非空,将2 1依次弹出压入q1。此时q2为空 q1为3 2 1。

4.
元素3出栈 q1非空 3出栈。q1为2
1 q2为空。

5.
元素4入栈 q2为空 压入。之前q1非空,将2 1依次弹出压入q2。此时q1为空 q2为4 2 1。

实现函数代码如下:

class QueueStack {
public:
// 保证每个时刻都有一个队列为空队列

// Push element x onto stack.
void push(int x) {
if(q1.empty())
{
q1.push(x);

while(!q2.empty())
{
q1.push(q2.front());
q2.pop();
}
}
else
{
q2.push(x);

while(!q1.empty())
{
q2.push(q1.front());
q1.pop();
}
}
}

// Removes the element on top of the stack.
void pop() {
if(q1.empty())
{
q2.pop();
}
else
{
q1.pop();
}
}

// Get the top element.
int top() {
if(q1.empty())
{
return q2.front();
}
else
{
return q1.front();
}
}

// Return whether the stack is empty.
bool empty() {
return (q1.empty() && q2.empty());
}

queue<int> q1;
queue<int> q2;
};
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: