用两个栈实现队列的功能

  • 我们知道队列可以用链表来实现,栈也可以用链表来实现,那么我们可不可以用栈来实现队列的功能呢?

实现方法:
假设两个栈 A B都为空,可以认为栈A提供入队列的功能,栈B提供出队列的功能。
入队列:入栈A

出队列:
* 如果栈B不为空,直接弹出栈B的数据。
* 如果栈B为空,则依次弹出栈A的数据,放入栈B中,再弹出栈B的数据。

实现如下:

#include<iostream>
#include<stack>
using namespace std;

template<class T>
struct MYQueue
{
    void push(T &t)
    {
        s1.push(t);
    }
    T front()
    {
        if (s2.empty())
        {
            if (s1.size() == 0) throw;
            while (!s1.empty())
            {
                s2.push(s1.top());
                s1.pop();
            }
        }
        return s2.top();
    }
    void pop()
    {
        if (s2.empty())
        {
            while (!s1.empty())
            {
                s2.push(s1.top());
                s1.pop();
            }
        }
        if (!s2.empty())
            s2.pop();
    }
    stack<T> s1;
    stack<T> s2;
};

int main()
{
    MYQueue<int> mq;
    int i;
    for (i = 0; i < 10; i++)
    {
        mq.push(i);
    }

    for (i = 0; i < 10; ++i)
    {
        cout << mq.front() << endl;
        mq.pop();
    }
    getchar();
    return 0;
}

猜你喜欢

转载自blog.csdn.net/awyyauqpmy/article/details/80465467