串行列队

实现一个串行队列,包含操作:入队、出队、获取队头的元素。

template 
class Queue {
private:
    int capacity;
    int head;
    int rear;
    T* buff;
    
public:
    Queue() : capacity(10), head(0), rear(0) {
        buff = new T[capacity];
    }
    
    Queue(int s) : capacity(s), head(0), rear(0) {
        buff = new T[capacity];
    }
    
    ~Queue() {
        capacity = 0;
        head = 0;
        rear = 0;
        delete [] buff;
    }
    
    bool isEmpty() {
        return head == rear ? true : false;
    }
    
    bool isFull() {
        return head == (rear + 1) % capacity ? true : false;
    }
    
    int getCapacity() {
        return capacity;
    }
    
    int size() {
        return head < rear ? rear - head : rear + capacity - head;
    }
    
    void enqueue(T data) {
        if (isFull()) {
            cout << "Error: Queue is full" << endl;
            throw bad_exception();
        }
        buff[rear] = data;
        rear = (rear + 1) % capacity;
    }
    
    void dequeue() {
        if (isEmpty()) {
            cout << "Error: Queue is empty" << endl;
            throw bad_exception();
        }
        buff[head] = 0;
        head = (head + 1) % capacity;
    }
    
    T getHeadElem() {
        if (isEmpty()) {
            cout << "Error: Queue is empty" << endl;
            throw bad_exception();
        }
        return buff[head];
    }
    
    int dequeueAll(T* elems, int maxSize) {
        assert(maxSize > 0);
        
        int size = 0;
        while (!isEmpty() && size < maxSize) {
            elems[size] = buff[head];
            buff[head] = 0;
            head = (head + 1) % capacity;
            size++;
        }
        return size;
    }
};

你可能感兴趣的:(串行列队)