//链表描述的队列类LinkedQueue
#include <iostream>
using namespace std;
template <class T>
class Node{
public:
T data;
Node<T> *link;
};
//FIIFO对象
template <class T>
class LinkedQueue{
public:
LinkedQueue(){front=rear=0;}
~LinkedQueue();
bool IsEmpty()const{return ((front)?false:true);}
bool IsFull()const;
T First()const; //返回队首元素
T Last()const; //返回队尾元素
LinkedQueue<T>& Add(const T& x);
LinkedQueue<T>& Delete(T& x);
void Output();
Node<T> *front; //指向第一个节点
Node<T> *rear; //最后一个节点
};
template <class T>
LinkedQueue<T>::~LinkedQueue(){
Node<T> *next;
while (front){
next = front->link;
delete front;
front = next;
}
}
class OutOfBounds{
public:
OutOfBounds(){
cout<<"Out Of Bounds!"<<endl;
}
};
//内存不足的异常类
class NoMem{
public:
NoMem(){
cout<<"No Memory!"<<endl;
}
};
//该队列的输出方法
template<class T>
void LinkedQueue<T>::Output(){
Node<T> *temp = front;
while(temp){
cout<<temp->data<<" ";
temp=temp->link;
}
cout<<""<<endl;
}
//判断当前队列是否已满
template <class T>
bool LinkedQueue<T>::IsFull()const{
Node<T>*p;
try{
p = new Node<T>;
delete p;
return false;
}
catch (NoMem)
{
return true;
}
}
//返回队列的第一个元素
template <class T>
T LinkedQueue<T>::First()const{
if(IsEmpty())
throw OutOfBounds();
return front->data
}
//返回队列的最后一个元素
template <class T>
T LinkedQueue<T>::Last()const{
if(IsEmpty())
throw OutOfBounds();
return rear->data
}
//将x添加到队列的尾部
template<class T>
LinkedQueue<T>& LinkedQueue<T>::Add(const T&x){
Node<T>*p = new Node<T>;
p->data=x;
p->link=0;
//在队列尾部添加新节点
if (front){
rear->link = p;
}
else{
front=p;
}
rear=p;
return *this;
}
//删除第一个元素并将其放到X中去
template<class T>
LinkedQueue<T>& LinkedQueue<T>::Delete(T&x){
if (IsEmpty()){
throw OutOfBounds();
}
x = front->data;
Node<T>*p = front;
front = front->link;
delete p;
return *this;
}
void main(){
LinkedQueue<int>myQueue;
myQueue.Add(5);
myQueue.Add(2);
myQueue.Add(0);
myQueue.Add(1);
myQueue.Add(3);
myQueue.Add(1);
myQueue.Add(4);
myQueue.Output();
int temp;
myQueue.Delete(temp);
myQueue.Delete(temp);
myQueue.Delete(temp);
myQueue.Output();
}
[C++]数据结构:链表描述的队列LinkedQueue类
最新推荐文章于 2023-07-13 23:07:49 发布