队列的实现

/****************************************************************************
*    队列的成员数据:队列的长度,队列头,队列尾,队列中元素个数;
*    队列的成员方法:初始化,是否为空,入队,出队,获取对列中元素。
*****************************************************************************/
#include<iostream>
//#define MAXSIZE 100
using namespace std;

//循环队列--数组形式
template<class T>
class Queue_
{
private:
	int Max_Size;
	int real;
	int font;
	T* data;
public:
	Queue_()
	{
		Max_Size=100;
		data=new T[Max_Size];
		real=font=-1;
	}
	~Queue_()
	{
		if(data!=NULL)
		{
			delete []data;
			cout<<"释放队列!"<<endl;
		}
	}
	bool Empty()
	{
		if(real==font)
		{
		//	cout<<"队列为空!"<<endl;
			return true;
		}else{
		//	
			return false;
		}
	}
	bool Full()
	{
		if((real-font==Max_Size-1)||(font==real+1))
		{
			//
			return true;
		}else{
			//
			return false;
		}
	}
	int GetSize()
	{
		if(!Empty())
		{
			return (real-font+Max_Size)%Max_Size;
		}else{
			return 0;
		}
	}
	T GetFont()
	{
		try
		{
			if(Empty())throw 0;
			return data[font];
		}catch(int e){
			if(e==0)cout<<"队列为空!"<<endl;
			exit(-1);
			
		}
	}
	bool En_Queue(T m_data)
	{
		if(Full())
		{
			return false;
		}else{
			if(real==-1)
			{
				real=0;
				font=0;
			}
			data[real]=m_data;
			real=(real+1)%Max_Size;
			return true;
		}
	}
	bool Out_Queue()
	{
		if(Empty())
		{
			return false;
		}else{
			font=(font+1)%Max_Size;
			return true;
		}
	}
};

int main()
{

	int a[]={5,3,2,7,9};
	Queue_<int> m_queue;
	if(m_queue.Empty())cout<<"队列为空!"<<endl;
	else cout<<"队列非空!"<<endl;
	if(m_queue.Full())cout<<"队列已满!"<<endl;
	else cout<<"队列未满!"<<endl;
	cout<<endl;

	m_queue.En_Queue(a[0]);
    m_queue.En_Queue(a[1]);
	m_queue.En_Queue(a[2]);
	m_queue.En_Queue(a[4]);
	if(m_queue.Empty())cout<<"队列为空!"<<endl;
	else cout<<"队列非空!"<<endl;
	if(m_queue.Full())cout<<"队列已满!"<<endl;
	else cout<<"队列未满!"<<endl;
	cout<<endl;
    cout<<"获取队列中元素个数: "<<m_queue.GetSize()<<endl;
	cout<<endl;

	cout<<"获取队列中对头元素: "<<m_queue.GetFont()<<endl;
	cout<<endl;

	if(m_queue.Out_Queue())cout<<"出队!"<<endl;
	cout<<endl;
	if(m_queue.Out_Queue())cout<<"出队!"<<endl;
	cout<<endl;
	if(m_queue.Out_Queue())cout<<"出队!"<<endl;
	cout<<endl;
	if(m_queue.Out_Queue())cout<<"出队!"<<endl;
	cout<<endl;
    cout<<"获取队列中元素个数: "<<m_queue.GetSize()<<endl;
	cout<<endl;

	//cout<<"获取队列中对头元素: "<<m_queue.GetFont()<<endl;
//	cout<<endl;

	m_queue.En_Queue(9);
    cout<<"获取队列中元素个数: "<<m_queue.GetSize()<<endl;
	cout<<endl;
	cout<<"获取队列中对头元素: "<<m_queue.GetFont()<<endl;
	cout<<endl;


	return 0;
}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值