#ifndef LINKEDQUEUE_H
#define LINKEDQUEUE_H
#include <iostream>
#include <assert.h>
using namespace std;
template<class T>
struct LinkNode //链式队列节点类的定义
{
T data; //数据域
LinkNode<T> *link; //链指针域
LinkNode(LinkNode<T> *ptr = NULL) //仅初始化指针成员的构造函数
{
link = ptr;
}
LinkNode(const T &item,LinkNode<T> *ptr = NULL) //初始化数据与指针成员的构造函数
{
data = item;
link = ptr;
}
};
template<class T>
class LinkedQueue
{
public:
LinkedQueue():front(NULL),rear(NULL){}
~LinkedQueue()
{
MakeEmpty();
}
bool EnQueue(const T& x); //将x加入到队列中
bool DeQueue(T& x); //删除队头元素,x返回其值
bool GetFront(T& x)const; //查看队头元素的值
void MakeEmpty(); //置空队列
bool IsEmpty()const
{
return (front == NULL) ? true : false;
}
int GetSize()const; //求队列元素个数
template<class T>
friend ostream& operator<<(ostream& os,LinkedQueue<T>& q);
private:
LinkNode<T> *front,*rear; //队头、队尾指针
};
template<class T>
void LinkedQueue<T>::MakeEmpty()
{
LinkNode<T> *p;
while(front != NULL)
{
p = front;
front = front->link;
delete p;
}
}
template<class T>
bool LinkedQueue<T>::EnQueue(const T &x)
{
if(front == NULL) //空队列时,新结点成为队列的第一个结点,既是队头又是队尾
{
front = rear = new LinkNode<T>(x);
if(front == NULL)
return false;
}
else //非空队列时,在链尾追加新的结点并更新队尾指针
{
rear->link = new LinkNode<T>(x);
if(rear->link == NULL)
return false;
rear = rear->link;
}
return true;
}
template<class T>
bool LinkedQueue<T>::DeQueue(T &x)
{
if(IsEmpty() == true)
return false;
LinkNode<T> *p = front;
x = front->data;
front = front->link;
delete p;
return true;
}
template<class T>
bool LinkedQueue<T>::GetFront(T &x) const
{
if(IsEmpty() == true)
return false;
x = front->data;
return true;
}
template<class T>
int LinkedQueue<T>::GetSize() const
{
LinkNode<T> *p = front;
int count = 0;
while(p != NULL)
{
++count;
p = p->link;
}
return count;
}
template<class T>
ostream& operator<<(ostream& os,LinkedQueue<T>& q)
{
os<<"队列中元素个数有"<<q.GetSize()<<"个。"<<endl;
LinkNode<T> *p = q.front;
int i = 0;
while(p != NULL)
{
os<<++i<<":"<<p->data<<endl;
p = p->link;
}
return os;
}
#endif