介绍
队列的链接存储结构及实现:
改造单链表实现队列的链接存储。
队头指针即为链表的头指针
类声明如下
———————————————————————————————————————————————————————————
实现代码
头文件LinkQueue.h
#ifndef LinkQueue_byNim
#define LinkQueue_byNim
#include<iostream>
using namespace std;
template<class T>
struct Node{
T data; //数据域
Node *next; //指针域
};
template<class T>
class LinkQueue
{
private:
Node<T> *front,*rear;
public:
LinkQueue();
~LinkQueue();
void EnQueue(T e);
T DeQueue();
T GetQueue();
bool empty();
};
template<class T>
LinkQueue<T>::LinkQueue() //构造函数
{
front=new Node<T>;
front->next=NULL;
rear=front;
}
template<class T>
LinkQueue<T>::~LinkQueue()
{
delete front;
}
template<class T>
void LinkQueue<T>::EnQueue(T e)
{
Node<T> *aNode;
aNode=new Node<T>;
aNode->data=e;
aNode->next=NULL;
rear->next=aNode;
rear=aNode;
}
template<class T>
T LinkQueue<T>::DeQueue()
{
if(rear==front) throw "下溢";
Node<T> *p;
p=front->next;
T x=p->data;
front->next=p->next;
if(p->next==NULL) rear=front; //边界情况队列中只有一个元素
delete p; //及时释放内存,避免内存泄漏
return x;
}
template<class T>
T LinkQueue<T>::GetQueue()
{
if(rear==front) throw "下溢";
return front->next->data;
}
template<class T>
bool LinkQueue<T>::empty()
{
if(rear==front)
return true;
return false;
}
#endif