以C++实现的数据结构与算法(队列)


队列


队列头文件可直接调用

#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;
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值