欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

数组实现队列

程序员文章站 2024-03-18 11:22:04
...

代码:

#include<iostream>
using namespace std;

template<class T>
class Queue {
private:
	int front;//队首元素所在数组元素下标
	int rear;//新元素要插入的位置
	int count;//当前队列中的元素个数
	T * Qarray;//存放队列的数组
	int maxsize;//存放队列的数组规模
public:
	Queue(int maxsize = 10);
	~Queue() {
		delete[]Qarray;

	}
	bool insertQ(const T& item);
	bool deleteQ();
	T peekQ();
	bool isEmpty() {
		if (count == 0)
			return true;
		else
			return false;
	}
	bool isFull() {
		if (count == maxsize)
			return true;
		else
			return false;
	}
};


template<class T>
Queue<T>::Queue(int maxsize)
{
	Qarray = new T[maxsize];
	front = 0;
	rear = 0;
	count = 0;
	this->maxsize = maxsize;
}

template<class T>
bool Queue<T>::insertQ(const T & item)
{
	if (isFull()) {
		cout << "队列已满,不可以插入新元素!" << endl;
		return false;
	}
	else {
		Qarray[rear] = item;
		rear++;
		rear = rear % maxsize;
		count++;
		return true;
	}
}

template<class T>
bool Queue<T>::deleteQ()
{
	if (isEmpty()) {
		cout << "队列为空,不可以删除元素" << endl;
		return false;
	}
	else {
		front++;
		front = front % maxsize;
		count--;
		return true;
	}
}

template<class T>
T Queue<T>::peekQ()
{
	T data;
	if (isEmpty()) {
		cout << "队列为空,不可以读取信息!" << endl;
		return NULL;
	}
	else {
		data=Qarray[front];
		return data;
	}
}

int main() {
	Queue<int> * queue = new Queue<int>(5);
	queue->deleteQ();
	queue->insertQ(1);
	queue->insertQ(2);
	queue->insertQ(3);
	queue->insertQ(4);
	queue->insertQ(5);
	queue->insertQ(6);
	int i=queue->peekQ();
	cout << "取数据:" << i << endl;
	queue->deleteQ();
	i = queue->peekQ();
	cout << "取数据:" << i << endl;
	queue->deleteQ();
	queue->deleteQ();
	queue->deleteQ();
	queue->deleteQ();
	queue->deleteQ();
	system("pause");
	return 0;

}
相关标签: 数据结构