隊列
先進先出(FIFO)
隊列的實現(xiàn)有很多種方法,靜態(tài)數(shù)組或動態(tài)數(shù)組或鏈表栅表,我們還是從有趣的“循環(huán)隊列”開始吧!
? 實現(xiàn)代碼如下:queue.h"
#pragma once
#include<iostream>
#include<string>
using namespace std;
/*
為了區(qū)別隊列空和滿师枣,我們空出一個元素怪瓶。
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;
}