您的位置:首页 > 编程语言 > C语言/C++

链队列介绍及其C++实现

2016-11-27 23:30 204 查看

介绍

队列的链接存储结构及实现:

改造单链表实现队列的链接存储。

队头指针即为链表的头指针

类声明如下



———————————————————————————————————————————————————————————

实现代码

头文件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
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: