队列

一、循环队列

循环队列中最重要的问题就是如何判断队空和队满,以下有三种解决方案

① 方法一: 浪费一个数组单元 设储存循环队列的数组的长度为QueueSize

队满:(rear + 1)%QueueSize = front

队空:front = rear;

template<class DataType>
void EnQueue(DataType x)
{
	//入队
	if((rear+1)%QueueSize == front)
		throw "上溢";
	//队尾指针在循环意义下加1
	rear = (rear+1)%QueueSize;
	data[rear]=x;
}

template<class DataType>
DataType DeQueue()
{
	//出队
	if(rear == front)
		throw "下溢";
	//对头指针在循环意义下加1
	front = (front+1)%QueueSize;
	return data[front];
}
② 方法二 设置一个标志flag

当front == rear 且 flag==0 为队空

当front == rear 且 flag==1 为队满

当有元素入队时,队列非空 所以将flag置1

当有元素出队时,队列不满 所以将flag置0

template<class DataType>
void EnQueue(DataType x)
{
	//入队
	if(rear == front && flag==1)
		throw "上溢";
	flag = 1;
	//队尾指针在循环意义下加1
	rear = (rear+1)%QueueSize;
	data[rear]=x;
}

template<class DataType>
DataType DeQueue()
{
	//出队
	if(rear == front && flag==0)
		throw "下溢";
	flag = 0;
	//对头指针在循环意义下加1
	front = (front+1)%QueueSize;
	return data[front];
}
③ 方法三 设置一个计数器count累计队列的长度

当count = 0时,队列为空

当count = QueueSize  队列为满

在类中设置一个私有成员变量count ,入队count加1,出队count减1

template<class DataType>
void CirQueue::EnQueue(DataType x)
{
	//入队
	if(count == QueueSize)
		throw "上溢";
	count++;
	//队尾指针在循环意义下加1
	rear = (rear+1)%QueueSize;
	data[rear]=x;
}

template<class DataType>
DataType CirQueue::DeQueue()
{
	//出队
	if(count == 0)
		throw "下溢";
	count--;
	//对头指针在循环意义下加1
	front = (front+1)%QueueSize;
	return data[front];
}
三、链队列
struct Node
{
	DataType data;
	Node<DataType> * next;
};
template<class DataType>
class LinkQueue
{
	public:
		LinkQueue();
		~LinkQueue();
		void EnQueue(DataType x);
		DataType DeQueue();
		DataType GetQueue();
		int Empty();
	private:
		Node<DataType> * front,* rear;
};
template<class DataType>
LinkQueue<DataType>::LinkQueue()
{
	Node<DataType> * s = NULL;
	s = new Node<DataType>;
	s->next = NULL;
	front = rear = s;
}
template<class DataType>
LinkQueue<DataType>::~LinkQueue()
{
	Node<DataType> * p = NULL;
	while(front!=NULL)
	{
		p=front->next;
		delete front;
		front=p;
	}
}
//入队
template<class DataType>
void LinkQueue<DataType>::EnQueue(DataType x)
{
	Node<DataType> * s = NULL;
	s = new Node<DataType>;
	s->data = x;
	s->next=NULL;
	rear->next=s; rear=s;
}
//出队
template<class DataType>
DataType LinkQueue<DataType>::DeQueue()
{
	Node<DataType> * p = NULL;
	DataType x;
	if(rear==front)
		throw "下溢";
	p=front->next;//含有一个头结点
	x=p->data;
	front->next=p->next;
	if(p->next==NULL)
		rear = front;
	delete p;
	return x;
}
//获取队头元素
template<class DataType>
DataType LinkQueue<DataType>::GetQueue()
{
	if(front!=rear)
		return front->next->data;
}
template<class DataType>
int LinkQueue<DataType>::Empty()
{
	if(front == rear)
		return 1;
	else
		return 0;
}



评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值