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

2021/7/10 20:38:11

本文主要是介绍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


这篇关于Deque(双向队列 c++模版实现 算法导论第三版第十章10.1-5题)的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!


扫一扫关注最新编程教程