【数据结构】使用deque作为底层数据结构,实现容器适配器栈

1. 库中queue的使用

代码如下:

#include 
#include 
using namespace std;
int main()
{
    priority_queue<int> q; //优先级队列
    //入队列
    q.push(1);
    q.push(2);
    q.push(3);
    q.push(4);

    cout << q.top() << endl; //4
    cout << q.size() << endl; //4

    //出队列
    q.pop();
    q.pop();

    cout << q.top() << endl; //2
    cout << q.size() << endl; //2

    return 0;
}

2. 使用deque实现容器适配器栈

代码如下:

#include 
using namespace std;
#include 

template<class T,int N = 7>
class Queue
{
public:
    Queue()
        :_front(0)
        , _rear(0)
        , _count(0)
    {}

    void Push(const T& data) 
    {
        assert(_count < N);
        _array[_rear] = data;
        _count++;
        _rear = (_rear + 1) % N;
    }

    void Pop() 
    {
        assert(_count);
        --_count;
        _front = (_front + 1) % N;
    }

    bool Empty()const 
    {
        return 0 == _count;
    }

    size_t Size()const
    {
        return _count;
    }

    T& Front() 
    {
        return _array[_front];
    }

    const T& Front()const
    {
        return _array[_front];
    }

    const T& Back()const
    {
        assert(_count);
        return _array[(_rear + N - 1) % N];
    }

private:
    T _array[N];
    int _front;
    int _rear;
    int _count;
};

int main()
{
    Queue q;
    q.Push(1);
    q.Push(2);
    q.Push(3);
    q.Push(4);
    q.Push(5);
    q.Push(6);

    cout << q.Size() << endl;
    cout << q.Front() << endl;
    cout << q.Back() << endl;

    q.Push(7);
    cout << q.Size() << endl;
    cout << q.Front() << endl;
    cout << q.Back() << endl;

    q.Pop();
    q.Pop();
    cout << q.Size() << endl;
    cout << q.Front() << endl;
    cout << q.Back() << endl;

    q.Pop();
    q.Pop();
    q.Pop();
    q.Pop();
    q.Pop();
    cout << q.Size() << endl;
    cout << q.Front() << endl;
    return 0;
}

你可能感兴趣的:(数据结构)