(六)链式队列

链式队列的尝试,总得来说还行。每次我都是照着写好类的原型,然后一个个的去实现,然后运行,查找错误和书上的区别。

在尝试链式队列是,就出现了一个问题。那就是在出队的时候,在队列为空的时候,有一个更改尾指针的过程:

if(front->next==NULL)rear=front;

开始的时候没有注意,导致输出的失败。

还有就是链式队列默认是带头节点的。没有充分认识这个特点,导致刚开始的时候代码有些混乱。我现在发现如果没有一个清晰的概念在脑子里,代码一多起来,就乱了。不是这个有一个问题,就是那里有一个问题。很烦人的……

下面是LinkQueue.h的代码:

#if !defined(_LinkQueue_H)
#define _LinkQueue_H
#include<iostream>
using namespace std;
template<class T>
struct Node
{
T data;
Node*next;
};
template<class T>
class LinkQueue
{
private:
Node<T>*front;
Node<T>*rear;
public:
LinkQueue();
~LinkQueue();
void EnQueue(T x);//入队
T DeQueue();//出队
T GetHead();//获得头元素
T GetLast();//获得尾元素
int QueueEmpty();//测队空
void ClearQueue();//清空队
void QueueDisplay();//游历遍队列数据
};
void From_Link();

template<class T>
void LinkQueue<T>::ClearQueue()
{
Node<T>*pi=front->next,*pj;
rear=front;
while(pi)
{
   pj=pi;
   pi=pi->next;
   delete pj;
}
cout<<"队列已清空!/n";
}
template<class T>
LinkQueue<T>::LinkQueue()
{
front=new Node<T>;
front->next=NULL;
rear=front;
}
template<class T>
LinkQueue<T>::~LinkQueue()
{
Node<T>*pi;
while(front)
{
   pi=front;
   front=front->next;
   delete pi;
}
}
template<class T>
void LinkQueue<T>::EnQueue(T x)
{
rear->next=new Node<T>;
if(!rear->next)
{
   cout<<"动态内存申请失败!/n";
   exit(1);
}
rear=rear->next;
rear->data=x;
rear->next=NULL;
}
template<class T>
T LinkQueue<T>::DeQueue()
{
if(front==rear)throw"队列为空,无法执行操作!/n";
Node<T>*pi=front->next;
T x=pi->data;
front->next=pi->next;
if(front->next==NULL) rear=front;
delete pi;
return x;
}
template<class T>
T LinkQueue<T>::GetHead()
{
if(front==rear)throw"队列为空,无法执行操作!/n";
return front->data;
}
template<class T>
T LinkQueue<T>::GetLast()
{
if(front==rear)throw"队列为空,无法执行操作!/n";
return rear->data;
}
template<class T>
void LinkQueue<T>::QueueDisplay()
{
Node<T>*pi=front->next;
int j=1;
if(front==rear)throw"队列为空!/n";
cout<<"队列中的元素为:/n";
while(pi)
{
   cout<<j<<"-->"<<pi->data<<endl;
   pi=pi->next;
   j++;
}
}
template<class T>
int LinkQueue<T>::QueueEmpty()
{
if(front==rear) return 1;
return 0;
}
#endif

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值