用链表搭建的栈与队列相对简单,队列的特点是先进先出,不啰嗦了,由于代码比较简单,相信光顾的人不会太多,下面直接贴代码。

头文件

 #ifndef QUEUELI_H
#define QUEUELI_H template<class T>
class Queue
{
public:
Queue();
~Queue(); bool isEmpty() const;
const T & getFront() const;
void enqueue(const T& x);
T dequeue();
void makeEmpty(); private: //也可以做一个友元类
struct ListNode
{
T element;
ListNode *next; ListNode(const T & theElement, ListNode *n=):
element(theElement), next(n){}
};
ListNode *front;
ListNode *back;
}; template<class T>
Queue<T>::Queue() //创建队列
{
front = back = ;
} template<class T>
Queue<T>::~Queue()//所有步骤执行完最后执行析构函数,清空队列
{
makeEmpty();
} template<class T>
void Queue<T>::makeEmpty()//清空队列
{
while (!isEmpty())
dequeue();
} template<class T>
bool Queue<T>::isEmpty() const
{
return front == ;
} template<class T>
const T & Queue<T>::getFront() const
{
if (isEmpty())
throw"Queue is empty.";
return front->element;
} template<class T>
void Queue<T>::enqueue(const T &x)
{
if (isEmpty())
back = front = new ListNode(x);
else
back = back->next = new ListNode(x);//队列在队尾插入结点
} template<class T>
T Queue<T>::dequeue()//删除队列
{
T frontItem = getFront();//留作返回要删除的结点中的值用
ListNode *old = front;
front = front->next;
delete old;
return frontItem;
} #endif

源文件-测试用

 #include<iostream>
#include"QueueLi.h" using namespace std; int main()
{
cout << "测试链式队列:" << endl; Queue<int> myQ; myQ.enqueue();
myQ.enqueue();
myQ.enqueue();
myQ.enqueue(); cout << myQ.getFront() << endl;
myQ.dequeue();
cout << myQ.getFront() << endl; return ;
}

最新文章

  1. 学习笔记:HSB、HSL
  2. css3的2D转换
  3. 简短的几句js实现css压缩和反压缩功能
  4. ABA problem
  5. Android Environment 判断sd卡是否挂载 获取sd卡目录
  6. python时间处理
  7. 【面试】惠普IT电面
  8. .net调用Outlook 批量发送邮件,可指定Outlook中的账号来发送邮件
  9. vue组件的那些事($children,$refs,$parent)的使用
  10. Net Core平台灵活简单的日志记录框架NLog+Mysql组合初体验
  11. MySQL-8.0.15在Win10和Ubuntu上安装&amp;使用
  12. 高手速成android开源项目【tool篇】
  13. Loadrunner11的安装方法和破解
  14. Bell(矩阵快速幂+中国剩余定理)
  15. 协程运行原理猜测: async/await
  16. linux convert mp3 to wav and opus to wav
  17. NC入门笔记
  18. iOS 用KVC设置结构体
  19. jQuery Validate自定义金钱验证,是否为金额格式,保留两位小数,并支持千分制货币格式
  20. PHP......会话控制SESSION与COOKIE

热门文章

  1. (转)RL — Policy Gradient Explained
  2. [原][资料整理][osg]osgDB文件读取插件,工作机制,支持格式,自定义插件
  3. openresty开发系列26--openresty中使用redis模块
  4. 八、postman的cookie支持
  5. MySQL创建双主键
  6. opencv4 mask_rcnn模型调(c++)
  7. 阿里云服务器Svn-Server无法连接
  8. Qt编写气体安全管理系统5-数据监控
  9. Flink 实现指定时长或消息条数的触发器
  10. pytorch 中Dataloader中的collate_fn参数