//3.5.07
//lQueue.h
//#include <iostream.h>
//#include <stdlib.h>
//ADT lQueue is
//Data
// 数据项列表
// front 表示队列中第一个数据项的位置
// rear 表示队列中最后一个数据项的位置
// count 任一时刻队列中元素项的个数
// Operations
// Constructor
// Initial values: 无
// Process: 初始化队头和队尾
// Length
// Input: 无
// Preconditions: 无
// Process: 确定队列中元素项的个数
// Output: 返回队列中元素项的个数
// Postconditions: 无
// Empty
// Input: 无
// Preconditions: 无
// Process: 检查队列是否为空
// Output: 若队列为空则返回1,否则返回0
// Postconditions: 无
// Delete
// Input: 无
// Preconditions: 队列非空
// Process: 从队列头部删除数据项
// Output: 返回被删除数据项
// Postconditions: 队列中删除一个数据项
// Insert
// Input: 要存到队列中的一个数据项
// Preconditions: 无
// Process: 将数据项放入到队尾
// Output: 无
// Postconditions: 一个新的数据项加到了队尾
// Front
// Input: 无
// Preconditions: 队列非空
// Process: 取出队列头部数据项的值
// Output: 返回队列头部数据项的值
// Postconditions: 无
// ClearQueue
// Input: 无
// Preconditions: 无
// Process: 删除队列中的所有数据项并重置初始状态
// Output: 无
// Postconditions: 队列为空
//end ADT lQueue
template <class T>
struct Node
{
T data;
Node<T> *next;
};
template <class T>
class lQueue
{
private:
int count;
Node<T> *head,*rear;
Node<T> *GetNode(const T &item,Node<T> *ptr=NULL);
public:
lQueue(void):count(0){head=NULL;rear=NULL;};
~lQueue(void);
//改变读列的操作
T Delete(void);
void Insert(T &item);
void ClearQueue(void);
//检测队列状态
int Length(void) const;
int Empty(void) const;
int Full(void) const;
//访问队列
T Front(void) const;
};
template <class T>
lQueue<T>::~lQueue(void)
{
Node<T> *temp;
while(head!=NULL)
{
temp=head;
head=head->next;
delete temp;
}
rear=NULL;
}
template <class T>
Node<T> *lQueue<T>::GetNode(const T &item,Node<T> *ptr)
{
Node<T> *temp;
temp=new Node<T>;
temp->data=item;
temp->next=ptr;
return temp;
}
template <class T>
void lQueue<T>::ClearQueue(void)
{
Node<T> *temp;
while(head!=NULL)
{
temp=head;
head=head->next;
delete temp;
}
rear=NULL;
}
template <class T>
void lQueue<T>::Insert(T &item)
{
if(count==0)
{
head=GetNode(item,NULL);
rear=head;
count++;
}
else if(count>0){
rear->next=GetNode(item,NULL);
rear=rear->next;
count++;
}
else {
cerr<<"error"<<endl;
exit(1);
}
}
template <class T>
T lQueue<T>::Delete(void)
{
T temp;
Node<T> *tempptr=NULL;
if(count<=0)
{
cerr<<"Atempt to QDelete an empty Queue"<<endl;
exit(1);
}
if(count==1)
{
temp=head->data;
delete head;
head=NULL;
rear=NULL;
count--;
}
else {
temp=head->data;
tempptr=head;
head=head->next;
delete tempptr;
count--;
}
return temp;
}
template <class T>
int lQueue<T>::Length(void) const
{
return count;
}
template <class T>
int lQueue<T>::Empty(void) const
{
return count==0;
}
template <class T>
T lQueue<T>::Front(void) const
{
if(count==0)
{
cerr<<"The queue is empty"<<endl;
exit(1);
}
return front->data;
}