第五章 隊列

隊列

先進先出(FIFO)

隊列的實現有很多種方法,靜態數組或動態數組或鏈表,我們還是從有趣的“循環隊列”開始吧!
? 實現代碼如下:queue.h"

#pragma once

#include<iostream>
#include<string>

using namespace std;

/*
為了區別隊列空和滿,我們空出一個元素。
FULL: (rear + 1)  % SIZE == front;
EMPTY: rear = front;
*/

template <typename T>
class Queue
{
public:
    Queue();
    bool isEmpty() const;
    bool isFull()const ;
    bool  enQueue(const T& e);
    bool deQueue(T& e);
    int length()const;
    void display(ostream& out) const;
private:
    int front;
    int rear;
    T *ele;
    const static int SIZE= 5;//實際只存儲4個值
};


template <typename T>
Queue<T>::Queue()
{
    ele = new T[SIZE];
    front = 0;//指向當前隊頭元素
    rear = 0;//指向末尾元素的下一位
}

template <typename T>
bool Queue<T>::isEmpty() const
{
    return  front == rear;//判斷空
}

template <typename T>
bool Queue<T>::isFull() const
{
    return  ( rear + 1 ) % SIZE == front;//判斷滿
}

template <typename T>
bool  Queue<T>::enQueue(const T& e)
{
    if (!isFull())
    {
        ele[rear] = e;
        rear = (rear + 1) % SIZE;//指針后移
    }
    else
    {
        return false;
    }
}

template <typename T>
bool  Queue<T>::deQueue( T& e)
{
    if (!isEmpty())
    {
        e = ele[front];
        front = (front + 1) % SIZE; // 指針后移
        return true;
    }
    else
    {
        return false;
    }
}

template <typename T>
int Queue<T>::length()const
{
    return (rear - front + SIZE) % SIZE;//長度計算
}

template <typename T>
void Queue<T>::display(ostream& out) const
{
    out << "front--->rear:" << endl;
    for (int i = front; i != rear; i = (i + 1) % SIZE)//迭代輸出
    {
        out << ele[i]<<" ";
    }
    out << endl;
}



最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容