一、循环队列
循环队列中最重要的问题就是如何判断队空和队满,以下有三种解决方案
① 方法一: 浪费一个数组单元 设储存循环队列的数组的长度为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;
}