队列
先进先出(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;
}