//LinkQueue.h
#ifndef LISTSTACK_H
#define LISTSTACK_H
#include <iostream>
using std::cout;
using std::endl;
template <class T>
struct Node
{
T data;
Node<T>*next;
};
template <class T>
class LinkQueue
{
public:
LinkQueue();
~LinkQueue();
void EnQueue(T x);
T DeQueue();
void Print();
T GetTop();
bool Empty();
int Length(){return length;}
private:
Node<T>*top,*rear;
int length;
};
template <class T>
LinkQueue<T>::LinkQueue()
{
top=new Node<T>; //有头结点
rear=top;
top->next=NULL;
length=0;
}
template <class T>
LinkQueue<T>::~LinkQueue()
{
while(top!=rear)
{
Node<T>*q=top;
top=top->next;
delete q;
}
delete top;
}
template <class T>
void LinkQueue<T>::EnQueue(T x)
{
Node<T>*s=new Node<T>;
s->data=x;
s->next=NULL;
rear->next=s;
rear=s;
length++;
};
template <class T>
T LinkQueue<T>::DeQueue()
{
if(rear==top) throw "下溢";
T x;
Node<T>*q=top->next;
x=q->data;
top->next=q->next;
if(q->next==NULL) rear=top;
delete q;
length--;
return x;
}
template <class T>
void LinkQueue<T>::Print()
{
Node<T>*p=top->next;
while(p!=rear)
{
cout<<p->data<<" ";
p=p->next;
}
cout<<p->data<<endl;
}
template <class T>
T LinkQueue<T>::GetTop()
{
if(top==rear) throw "下溢";
return (top->next)->data;
}
template <class T>
bool LinkQueue<T>::Empty()
{
return top->next==NULL? 1:0;
}
#endif
//main.cpp
#include "LinkQueue.h"
void main()
{
int a[5]={1,2,3,4,5};
LinkQueue<int> l;
for(int i=0;i<5;i++)
l.EnQueue(a[i]);
cout<<"该链队列为:";
l.Print();
cout<<"length="<<l.Length()<<endl;
cout<<"对头元素为:"<<l.GetTop()<<endl;
cout<<"出队列的元素分别为:"<<l.DeQueue()<<" ";
cout<<l.DeQueue()<<endl;
cout<<"此时该链队列为:";
l.Print();
cout<<"length="<<l.Length()<<endl;
cout<<"对头元素为:"<<l.GetTop()<<endl;
if(l.Empty())
cout<<"该链队列为空"<<endl;
else
cout<<"该链队列不为空"<<endl;
cout<<"剩余元素依次出队:";
for(int j=0;j<3;j++)
cout<<l.DeQueue()<<" ";
cout<<endl<<"此时对头元素:";
try
{
cout<<l.GetTop()<<endl;
}
catch(char*)
{
cout<<"不存在!!!!"<<endl;
}
}