队列实现栈

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

class myStack
{
public:
    void push(int a);

    int pop();

    int top();

    bool empty();

private:
    queue<int> _data;
};

void myStack::push(int a)
{
    queue<int> temp;
    temp.push(a);
    while(!_data.empty())
    {
        temp.push(_data.front());
        _data.pop();
    }

    while(!temp.empty())
    {
        _data.push(temp.front());
        temp.pop();
    }
}

int myStack::pop()
{
    int i = _data.front();
    _data.pop();
    return i;
}

int myStack::top()
{
    return _data.front();
}

bool myStack::empty()
{
    return _data.empty();
}

int main()
{
    myStack __myStack;


    for(int i = 0; i < 5; ++i)
    {
        __myStack.push(i);
        cout << __myStack.top() << endl;
    }
    return 0;
}

  

原文地址:https://www.cnblogs.com/11ys/p/14266074.html