Deque(双向队列 c++模版实现 算法导论第三版第十章10.1-5题)

Deque(双向队列 c++模版实现 )

算法导论第三版第十章10.1-5题

#ifndef C11LEARN_DEQUE_H
#define C11LEARN_DEQUE_H
template<typename T>
class Deque
{
private:
    int capacity;
    T*array;
    int head;
    int tail;
public:
    Deque(int capacity = 20);
    Deque(const Deque<T>& deque);
    Deque<T>& operator=(const Deque<T>& deque);
    virtual ~Deque();
    void head_enqueue(const T &element);
    T head_dequeue();
    void tail_enqueue(T &element);
    T tail_enqueue();
    bool empty();
    bool full();
};
template<typename T>
Deque<T>::Deque(int capacity):capacity(capacity){
    if(this->capacity<20)
        this->capacity = 20;
    array = new T[capacity];
    head = tail = 0;
}
template<typename T>
Deque<T>::Deque(const Deque<T>& deque){
    capacity = deque.capacity;
    array = new T[capacity];
    head = deque.head;
    tail = deque.tail;
    for (int i = 0; i < capacity; ++i) {
        array[i] = deque.array[i];
    }
}
template<typename T>
Deque<T>::~Deque() {
    delete[] array;
}
template<typename T>
Deque<T>& Deque<T>::operator=(const Deque<T>& deque){
    if(array!= nullptr)
        delete[] array;
    capacity = deque.capacity;
    array = new T[capacity];
    head = deque.head;
    tail = deque.tail;
    for (int i = 0; i < capacity; ++i) {
        array[i] = deque.array[i];
    }
}
template<typename T>
void Deque<T>::head_enqueue(const T &element){
    if(full())
        throw "overflow";
    head--;
    if(head<0)
        head  = capacity - 1;
    array[head] = element;
}
template<typename T>
T Deque<T>::head_dequeue(){
    if(empty())
        throw "underflow";
    T element = array[head];
    head++;
    if(head == capacity)
        head = 0;
    return element;
}
template<typename T>
void Deque<T>::tail_enqueue(T &element){
    if(full())
        throw "overflow";
    array[tail] = element;
    if(tail == capacity - 1)
        tail = 0;
    else
        tail++;
}
template<typename T>
T Deque<T>::tail_enqueue(){
    if(empty())
        throw "underflow";
    tail--;
    if(tail < 0)
        tail = capacity - 1;
    return  array[tail];
}
template<typename T>
bool Deque<T>::empty(){
    return head == tail;
}
template<typename T>
bool Deque<T>::full(){
    return head == (tail + 1 == capacity ? 0 : tail + 1);
}
#endif //C11LEARN_DEQUE_H
上一篇:P4655 [CEOI2017]Building Bridges


下一篇:No.2 纸牌-小猫钓鱼