//链队列,c++实现
#include <iostream>
using namespace std;
template <class Telem> class Queue
{
public:
virtual void init()=0; //初始化
virtual int leng()=0; //求长度
virtual bool full()=0; //判队列满
virtual bool empt()=0; //判空队列
virtual bool enque (Telem el)=0;
//将el存入队列,操作成功返回true否则返回false
virtual Telem dlque()=0;
//若队列非空则返回队头元素且删除队头元素,否则返回NULL
virtual Telem getf()=0;
//若队列非空返回队头元素,否则返回NULL
};
template <class Telem> class LinkQueue;
template <class Telem> class Node
{
friend class LinkQueue <Telem>;
Telem data;
Node <Telem> *next;
public:
Node(Telem d=0,Node <Telem> *n=NULL):data(d),next(n){};
};
template <class Telem>
class LinkQueue :public Queue<Telem>
{
private:
Node <Telem> *front,*rear;
public:
LinkQueue()//功能:生成一个附加结点,由front及rear指向,并将该结点的指针域设置为NULL。
{
Node <Telem> *p;
p=new Node <Telem>;
p->next=NULL;
front=rear=p;
}
~LinkQueue()//功能:顺链释放链队列中所有结点的存储空间。
{
Node <Telem> *p,*q;
p=front;
while(p!=rear){
q=p;
p=p->next;
delete q;
};
delete p;
}
void init(){ front->next=NULL; rear=front; };
int leng();
bool enque(Telem el);
Telem dlque();
Telem getf(){return front->next->data;};
bool empt(){return front==rear;};
bool full(){return false;};
};
template <class Telem> int LinkQueue <Telem>::leng()
{
Node <Telem> *p;
int i;
p= front->next;
i=0;
while (p!= NULL ) {
i++;
p=p->next;
}
return i;
};
template <class Telem> bool LinkQueue <Telem>::enque(Telem el)
{
Node <Telem> *p;
p= new Node <Telem>;
p->data=el;
p->next=NULL;
rear->next=p;
rear=p;
return true;
};
template <class Telem> Telem LinkQueue <Telem>::dlque()
{
Node <Telem> *s; Telem el;
if (front==rear)
return NULL;
else {
s=front->next;
front->next=s->next;
if (s->next==NULL )
rear =front;
el=s->data;
delete s;
return el;
}
};
void prnt(Queue<char>& q)
{
LinkQueue<char> sq; char ch;
while(!q.empt())
{
ch=q.dlque();
cout<<ch<<" ";
sq.enque(ch);
}
cout<<endl;
while(!sq.empt())
{
ch=sq.dlque();
q.enque(ch);
}
}
int main(){
LinkQueue<char> lq;
lq.enque('x');
lq.enque('w');
lq.enque('y');
lq.enque('g');
lq.enque('j');
prnt(lq);
cout<<lq.dlque()<<endl;
cout<<lq.dlque()<<endl;
cout<<lq.getf()<<endl;
prnt(lq);
return 0;
}