用两个栈模拟一个队列

栈是后进先出,队列是先进先出。

插入元素时,向栈stack1插入,比如插入a,b,c。

现在模拟取出元素,如果直接从stack1中pop,这时会弹出c。我们可以从stack1中把所有元素pop,放入stack2中,这时候stack2中是c,b,a。这时对stack2进行pop操作,取出的就是a了,stack2现在元素为c,b。这时在考虑向队列中插入d,向stack1中放入d,然后队列进行pop操作,stack2.pop(),取出b,符合实际。再一次进行pop,stack2弹出c,再次弹出,stack1弹出d,插入stack2中,stack2再次pop,弹出d。符合队列的先进先出。

参考代码如下:

#include <iostream>
#include <stack>
#include <exception>

using namespace std;

template <typename T> class CQueue
{
public:
    CQueue(){};
    ~CQueue(){};
    T top();//取出队首元素
    void pop();//删除操作
    void push(const T& t);//插入操作
private:
    stack<T> stack1;
    stack<T> stack2;

};

template <typename T>
void CQueue<T>::push(const T& t){
    stack1.push(t);
}

template <typename T>
T CQueue<T>::top()
{
    if( stack2.empty()){
        while( !stack1.empty() ){
            T& data = stack1.top();
            stack1.pop();
            stack2.push(data);
        }
    }//如果stack2为空,则将stack1中元素全部弹出到stack2中
    try{
        if(stack2.empty())
            throw  exception("queue is empty");
        T head = stack2.top();
        return head;
    }catch(exception& c){
        cerr<<c.what()<<endl;
    }
}

template <typename T>
void CQueue<T>::pop()
{
    if( stack2.empty()){
            while( !stack1.empty() ){
                T& data = stack1.top();
                stack1.pop();
                stack2.push(data);
            }
        }
        try{
            if(stack2.empty())
                throw  exception("queue is empty");
            stack2.pop();
        }catch(exception& c){
            cerr<<c.what()<<endl;
        }
}

int main()
{
    char a;
    CQueue<char> c1;

    c1.top();//测试用例1,对空队列进行删除和插入操作
    c1.push('a');
    c1.push('b');//测试用例2,对非空队列进行插入删除操作
    c1.push('c');
    a=c1.top();
    c1.pop();
    c1.push('d');
    c1.pop();
    c1.pop();
        c1.pop();//测试用例3,连续删除元素直至队列为空
    return 0;
}

 

posted @ 2013-04-19 21:04  yitianke  阅读(1304)  评论(0编辑  收藏  举报