队列
队列头文件可直接调用
#pragma once
#include<iostream>
using namespace std;
template<class T>
class LinearQueue {
public:
LinearQueue(int maxSize);
~LinearQueue();
bool isEmpty();
bool isFull();
bool insert(const T&x);
bool getElement(T&x);
bool Delete(T&x);
void outPut(ostream&cout)const;
private:
int size;//实际元素个数
int maxSize;
int front, rear;
T*element;
};
//实现构造函数
template<class T>
LinearQueue<T>::LinearQueue(int maxSize) {
this->maxSize = maxSize;
element = new T[maxSize];
size = 0;
front = 0;
rear = 0;
}
//实现析构函数
template<class T>
LinearQueue<T>::~LinearQueue() {
delete[]element;
}
//实现判断队列是否为空
template<class T>
bool LinearQueue<T>::isEmpty() {
return size == 0;
}
//实现判断队列是否为满
template<class T>
bool LinearQueue<T>::isFull() {
return size == maxSize;
}
//实现入队
template<class T>
bool LinearQueue<T>::insert(const T&x) {
if (isFull()) {
return false;
}
else {
element[rear] = x;
rear = (rear + 1) % (maxSize);
size++;
return true;
}
}
//实现求队头元素
template<class T>
bool LinearQueue<T>::getElement(T&x) {
if (isEmpty()) {
return false;
}
else {
x = element[front];
return true;
}
}
//实现出队
template<class T>
bool LinearQueue<T>::Delete(T&x) {
if (isEmpty()) {
return false;
}
else {
x = element[front];
front = (front + 1) % (maxSize);
size--;
return true;
}
}
//重载
template<class T>
void LinearQueue<T>::outPut(ostream&cout)const {
int index;
index = front;
for (int i = 0; i < size; i++)
{
cout << element[index] << endl;
index = (index + 1) % maxSize;
}
}
template<class T>
ostream&operator<<(ostream&cout, const LinearQueue<T>&x) {
x.outPut(cout);
return out;
}