队列链式存储结构的C++模板类头文件源代码实现

队列的链式存储结构与链表的区别除了成员函数的不同以外,还有队列的成员变量增加了尾指针,这是因为增加变量需要从链表的尾部添加,若每次从头结点开始遍历的话太费时间,头指针是一个空数据的节点指针,它是一个一直存在的指针,rear指针指向队列的最后一个元素,当最后一个元素也删除时,将rear指针赋值给front,这样队列就满足了队列为空的条件。下面是队列链式存储结构的C++模板类头文件源代码:

//linkedqueue.h
#ifndef LINKEDQUEUE_H
#define LINKEDQUEUE_H
#include <IOSTREAM>
template<class Type>
struct LNode{
Type data;
LNode<Type>* next;
};
template<class Type>
class LinkedQueue
{
private:
LNode<Type>* front,* rear;
public:
LinkedQueue();
~LinkedQueue();
bool AddElement(Type);
Type DeleteElement();
bool IsEmpty();
void Print();
};
template<class Type>
LinkedQueue<Type>::LinkedQueue()
{
front=new LNode<Type>;
rear=front;
front->next=NULL;
front->data=(Type)-111;
}
template<class Type>
LinkedQueue<Type>::~LinkedQueue()
{
LNode<Type>* temp=front;
while(temp)
{
LNode<Type>* tempvalue=temp;
temp=temp->next;
delete tempvalue;
}
}
template<class Type>
bool LinkedQueue<Type>::AddElement(Type x)
{
LNode<Type>* temp=new LNode<Type>;
temp->data=x;
temp->next=NULL;
rear->next=temp;
rear=temp;
return true;
}
template<class Type>
Type LinkedQueue<Type>::DeleteElement()
{
if(front==rear)
return Type(-111);
LNode<Type>* temp=front->next;
front->next=front->next->next;
Type x=temp->data;
if(temp==rear)
rear=front;
delete temp;
return x;
}
template<class Type>
bool LinkedQueue<Type>::IsEmpty()
{
return (front==rear?true:false);
}
template<class Type>
void LinkedQueue<Type>::Print()
{
LNode<Type>* temp=front->next;
while(temp)
{
std::cout<<temp->data<<" ";
temp=temp->next;
}
std::cout<<std::endl;
}
#endif

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值