//LinkQueue.h
#ifndef LinkQueue_H
#define LinkQueue_H
#include<iostream>
using namespace std;
template<class T>
struct Node
{
T data;
Node<T> *next;
};
template<class T>
class LinkQueue
{
public:
LinkQueue();
~LinkQueue(){}
void EnQueue(T x);
T GetQueue();
T DeQueue();
int Empty();
private:
Node<T> *front,*rear;
};
#endif
//LinkQueue.cpp
#include"LinkQueue.h"
template<class T>
LinkQueue<T>::LinkQueue()
{
Node<T> *s;
s=new Node<T>;s->next=NULL;
front=rear=s;
}
template<class T>
void LinkQueue<T>::EnQueue(T x)
{
Node<T> *s;
s=new Node<T>;s->data=x;
s->next=NULL;rear->next=s;
rear=s;
}
template<class T>
T LinkQueue<T>::GetQueue()
{
if(front=rear)throw"下溢";
Node<T>*p;int x;
p=front->next;x=p->data;
return x;
}
template<class T>
T LinkQueue<T>::DeQueue()
{
if(front=rear)throw"下溢";
Node<T>*p;int x;
p=front->next;x=p->data;
front->next=p->next;
if(p->next==NULL)rear=front;
return x;
delete p;
}
template<class T>
int LinkQueue<T>::Empty()
{
if(front->next=NULL)return 1;
if(front=rear)return 1;
else return 0;
}
//MainLinkQueue.cpp
#include"LinkQueue.cpp"
#include<iostream>
using namespace std;
void main()
{
LinkQueue<int>a;
int data[8]={1,2,3,4,5,6,7,8};
cout<<"等待入队元素依次为:1,2,3,4,5,6,7,8"<<endl;
cout<<"执行入操作:"<<endl;
for(int i=1;i<=8;i++)
{
a.EnQueue(data[i-1]);
}
cout<<"入队元素依次为:1,2,3,4,5,6,7,8"<<endl;
cout<<"取队头元素:"<<endl;
try
{
cout<<a.GetQueue();
}
catch(char *wrong)
{
cout<<wrong<<endl;
}
cout<<"删除队尾元素:"<<endl;
try
{
a.DeQueue();
}
catch(char *wrong)
{
cout<<wrong<<endl;
}
cout<<"判断队列是否为空:"<<a.Empty()<<endl;
cout<<"依次删除队中元素:"<<endl;
try
{
for(int i=1;i<=8;i++)
cout<<a.DeQueue()<<endl;
}
catch(char*wrong)
{
cout<<wrong<<endl;
}
cout<<"判断队列是否为空:"<<a.Empty()<<endl;
cout<<"取队头元素并执行删除队尾元素操作"<<endl;
try
{
cout<<a.GetQueue()<<" ";
cout<<a.DeQueue()<<endl;
}
catch(char*wrong)
{
cout<<wrong<<endl;
}
}