数据结构栈模拟队列

2017-06-23 19:15:16

队列时先进先出型,而栈是先进后出型,这就需要建立一个联系。我想到的一个简单的表示方式是:

这样就需要两个栈,栈1是用来实现add操作,即直接push进去就行;栈2实现poll和peek操作,具体来说就是首先判断是否为空,若为空那么则将栈1的数据依次压入栈2,若不为空,则直接操作即可。

class Myqueue
{
    stack<int> s1;
    stack<int> s2;
public:
    void add(int key) {s1.push(key);}

    void peek()
    {
        if(s2.empty())
        {
            while(!s1.empty()) 
            {
                s2.push(s1.top());
                s1.pop();
            }
            if(s2.empty()) cout<<"当前队列为空\n";
            else s2.pop();
        }
        else s2.pop();
    }

    void poll()
    {
        if(s2.empty())
        {
            while(!s1.empty()) {s2.push(s1.top());s1.pop();}
            if(s2.empty()) cout<<"当前队列为空\n";
            else cout<<s2.top()<<endl;
        }
        else cout<<s2.top()<<endl;
    }
};
原文地址:https://www.cnblogs.com/hyserendipity/p/7071429.html