1. 程式人生 > >迴圈佇列的實現(Queue, C++版)

迴圈佇列的實現(Queue, C++版)

/* Queue.h */
#ifndef __QUEUE_H__
#define __QUEUE_H__

#include <iostream.h>

extern "C" { void exit(int); }

const int nDefaultQueueSize = 50;

template <class T>
class Queue {
private:
    T   *qlist; //存放佇列元素的指標(陣列)
    int size; //佇列大小(容量)
    int front; //隊首位置
    int rear; //隊尾位置(最後一個元素的下一位置)
    int count; //佇列中元素的個數
public:
    //建構函式
    Queue(int initSize=nDefaultQueueSize) {
        if (initSize < 1)
            initSize = nDefaultQueueSize;
        qlist = new T[initSize];
        if (!qlist) {
            cerr << "儲存空間分配失敗,應用程式將終止!"
                 << endl;
            exit(1);
        }
        front = 0;
        rear = 0;
        count = 0;
        size = initSize;
    }
    //解構函式
    ~Queue() {
        if (qlist) delete [] qlist;
        front = 0;
        rear = 0;
        count = 0;
        size = 0;
    }
    //判斷佇列是否為空
    int QEmpty() {
        //return front == rear;
        return count == 0;
    }
    //判斷佇列是否已滿
    int QFull() {
        //return (rear+1) % size == front;
        return count == size;
    }
    //佇列長度
    int QLength() {
        return count;
        //return (rear - front + size) % size;
    }
    //隊尾插入(追加)元素
    void QInsert(const T &item) {
        if (count == size) {
            cerr << "佇列已滿,無法再追加元素。"
                 << endl;
            return;
        }
        count ++;
        qlist[rear] = item;
        rear = (rear + 1) % size; //rear始終指向最後一個元素的下一個位置
    }
    //隊首刪除元素
    T QDelete(T &data) {
        if (count > 0) {
            data = qlist[front];
            count --;
            front = (front + 1) % size; //front移向下一位置
        }
        else
            cerr << "佇列已空,無法繼續刪除。" << endl;
        return data;
    }
    //讀取隊首元素
    T QFront(T &data) {
        if (count > 0)
            data = qlist[front];
        else
            cerr << "佇列為空,無法讀取隊首元素的值。" << endl;
        return data;
    }
    //清空佇列
    void ClearQueue() {
        front = 0;
        rear = 0;
        count = 0;
    }
};

#endif /* !__QUEUE_H__ */

////////////////////////////////////////////////////////////
// QueueTest.cpp
#include "Queue.h"
void main()
{
    Queue<int>  Q;
    int e;

    Q.QInsert(100);
    cout << "front : " << Q.QFront(e) << endl;
    Q.QInsert(256);
    cout << "Length : " << Q.QLength() << endl;
    Q.QDelete();
    cout << "Length(After deleted) : " << Q.QLength() << endl;
}