这个问题似乎很经典,在很多的地方都看得到,对于大部分人来说这个问题很easy,但我想把自己的设计过程简单说明一下,以记一下这个设计的流程。
思路很简单,栈的操作跟出栈操作和队列不同,通俗的讲正好相反,所以反反为正的原则告诉我们,用两个栈就能模拟一个队列了。假如有两个栈stack1,和stack2。stack1用来负责存放入栈的序列,而stack2负责整个队列的出栈操作。当有入栈需求时,我们直接把数据存放入stack1就行了,而当有出栈需求时,我们就需要判断了,因为可能会遇到栈空的现象。当系统希望出栈时,我们首先判断stack2是否为空,如果stack2不空,说明里面有元素供我们使用,直接拿来就行了,所以直接选择让stack2出栈,然后返回就行了;但如果stack2为空怎么办呢?这个时候我们就要去看stack1的情况了,试着将stack1中的所有元素都出栈道stack2中,我们先不用去管stack1中是否有元素(当stack2为空的时候,就把stack1中的元素都存放到stack2中),取完了stack1中的元素后,可能有人会问假如stack1中也为空怎么办?对,这个是很重要的一个判断,也是下一步需要检测的内容,我们在这个时候再去判断stack2是否为空,这个时候如果stack2再为空的时候,就说明系统在做一个违法的操作--试图让一个为空的队列尝试出队列的操作。所以给出相应的警告提示!因为C++中的栈数据结构使用比较方便,所以采用C++进行了设计。 下面是我的的代码:
QueueWithTwoStacks.h
#include <stack>
#include <exception>
#include <iostream>
using namespace std;
template <typename T> class CQueue{
public:
CQueue();
~CQueue();
void appendTail(const T& node);
T deleteHead();
private:
stack<T> stack1;
stack<T> stack2;
};
template <typename T> CQueue<T>::CQueue(){}
template <typename T> CQueue<T>::~CQueue(){}
template <typename T> void CQueue<T>::appendTail(const T& node){
stack1.push(node);
}
template <typename T> T CQueue<T>::deleteHead(){
if(stack2.size() <= 0) {
while(stack1.size() > 0){
T& tmp = stack1.top();
stack1.pop();
stack2.push(tmp);
}
}
if(stack2.size() == 0){
//throw new exception("queue is empty!");
cout << "queue is empty" << endl;
return NULL;
}
T popElement = stack2.top();
stack2.pop();
return popElement;
}
test.cc
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
#include "QueueWithTwoStacks.h" int main(){ CQueue<char> fxp; fxp.appendTail('a'); fxp.appendTail('b'); fxp.appendTail('c'); cout << fxp.deleteHead() << endl; cout << fxp.deleteHead() << endl; cout << fxp.deleteHead() << endl; }
说明:如果采用了模板的话,最好不要将实现和头文件分开,也就是不要使用离散编译的方法,因为目前大多数的C++编译器对模板离散编译还不支持。