//
// Created by 35b002 on 2019/2/16.
//

#include "sequential_queue.h"


template <typename T>
SequentialQueue<T>::SequentialQueue(int maxsize) {

    _maxsize = maxsize;
    _elements = new T[_maxsize];
    _size = 0;

    _front_pointer = 0;
    _rear_pointer = 0;
}


template <typename T>
SequentialQueue<T>::~SequentialQueue() {

    delete[] _elements;
}


template <typename T>
void SequentialQueue<T>::Enqueue(T x) {

    // 当队列非空，但是队尾已经循环后，和队首重合
    // 不再对队尾进行操作，防止覆盖数据
    if (_size != 0 && _rear_pointer == _front_pointer) {
        return;
    }

    _elements[_rear_pointer] = x;

    int new_rear_pointer = _rear_pointer + 1;
    _rear_pointer =
            (new_rear_pointer >= _maxsize) ?
            new_rear_pointer - _maxsize: new_rear_pointer;
    _size++;
}


template <typename T>
T SequentialQueue<T>::Dequeue() {

    if (_size == 0) { // 队空，返回
        return NULL;
    }
    T temp = _elements[_front_pointer];

    int new_front_pointer = _front_pointer + 1;
    _front_pointer =
            (new_front_pointer >= _maxsize) ?
            new_front_pointer - _maxsize: new_front_pointer;

    _size--;
    return temp;
}

template <typename T>
void SequentialQueue<T>::Display() {

    if (_size == 0) {
        std::cout << "empty" << std::endl;
    }
    for(int i = 0; i < _size; ++i) {
        int pointer = i + _front_pointer;
        pointer = (pointer >= _maxsize) ?
                  pointer - _maxsize:
                  pointer;
        std::cout << _elements[pointer] << std::endl;
    }
}