一、引言
在前面的文章中笔者分别分享了栈和队列的实现,我们可以发现栈的特性(先进后出)和队列的特性(先进先出)似乎存在某种相似性。那么二者之间有没有什么互相的关联呢?
二、用两个栈结构来实现队列
对于队列,我们通常使用的是两个操作:
- 在队列尾部插入节点
- 在队列头部删除节点
根据栈和队列的特性,我们很容易想到如何使用两个栈(stack1,stack2)来实现队列。
算法描述:
- 删除节点:元素先依次压入stack1,然后再从stack1中取出压入stack2(此过程满足栈的“先进后出”)。当stack2中不为空时,stack2中的栈顶元素是最先进入队列的元素,可以弹出。
- 插入节点:直接压入stack1即可。
代码实现:
class QueueWithTwoStacks
{
public:
QueueWithTwoStacks();
~QueueWithTwoStacks();
void enqueue(const int element);
int dequeue();
private:
stack<int> stack1;
stack<int> stack2;
};
void QueueWithTwoStacks::enqueue(const int element)
{
stack1.push(element);
}
int QueueWithTwoStacks::dequeue()
{
//stack2为空且stack1不为空,则将stack1中元素全部压入stack2
if (stack2.size() <= 0)
{
while (stack1.size() > 0)
{
int data = stack1.top(); //取出栈顶元素
stack1.pop(); //删除栈顶元素
stack2.push(data); //压入stack2
}
}
if (stack2.size() == 0)
throw new exception("The queue is empty!");
int head = stack2.top();
stack2.pop();
return head;
}