C++之顺序队

#include <iostream>
using namespace std;

template <class T>
class LinearQueue {
public:
	LinearQueue(int LQMaxSize);
	~LinearQueue();

	bool IsEmpty();
	bool IsFull();
	bool Insert(const T& x);
	bool GetElement(T& x);//将队头元素的值放入x中
	bool Delete(T& x);
	void OutPut(ostream& out) const;

private:
	int MaxSize;
	int front, rear;

	int size;//队列实际元素个数
	T* elem;//一维动态数组
};

template <class T>
LinearQueue<T>::LinearQueue(int LQMaxSize) {
	MaxSize = LQMaxSize;
	elem = new T[LQMaxSize];
	size = 0;
	front = 0;
	rear = 0;
}

template<class T>
LinearQueue<T>::~LinearQueue()
{
	delete []elem;
}

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 {
		elem[rear] = x;
		rear = (rear + 1) % (MaxSize);
		size++;
		return true;
	}
}

template<class T>
bool LinearQueue<T>::GetElement(T& x)
{
	if (IsEmpty())
		return false;
	else {
		x = elem[front];
		return true;
	}
}

template<class T>
bool LinearQueue<T>::Delete(T& x)
{
	if (IsEmpty())
		return false;
	else {
		x=elem[front];
		front = (front + 1) % (MaxSize);
		
		size--;
		return true;
	}
}

template<class T>
void LinearQueue<T>::OutPut(ostream& out) const
{
	int index;
	index = front;
	for (int i = 0; i < size; i++) {
		out << elem[index] << endl;
		index = (index + 1) % (MaxSize);
	}
}


template <class T>
ostream& operator<<(ostream& out, const LinearQueue<T>& x) {
	x.OutPut(out);
	return out;
}

int main() {
	LinearQueue<int> q(10);
	q.Insert(100);
	q.Insert(200);

	cout << q;

	return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值