链队列的C++实现及其应用
来源:互联网 发布:无线路由里访客网络 编辑:程序博客网 时间:2024/06/04 17:50
队列是先进先出的数据结构,符合世间万物先到先得的处理顺序。本文将列出如何实现队列。本文使用链表加上头指针和尾指针构成了队列,其中头指针指向队头元素的上一个节点(头结点),尾指针指向队尾元素。
链队列实现
- 头文件定义在LinkQueue.h:
#ifndef LINKQUEUE_H_INCLUDED#define LINKQUEUE_H_INCLUDEDusing Type = int;typedef struct node{ Type data; node *next;}node,*nodePtr;class LinkQueue {private: nodePtr front; nodePtr rear;public: LinkQueue(); bool DestroyQueue(); bool ClearQueue(); bool isEmpty(); int length(); bool getHead(Type &e); bool push(Type &e); bool pop(Type &e);};#endif // LINKQUEUE_H_INCLUDED
- 具体函数定义在LinkQueue.cpp:
#include "LinkQueue.h"LinkQueue::LinkQueue(){ front = rear = new node; front->next = nullptr;}bool LinkQueue::DestroyQueue(){ while(front){ rear = front->next; delete front; front = rear; } return true;}bool LinkQueue::ClearQueue(){ nodePtr t; t = front; front=front->next; DestroyQueue(); front=rear=t; front->next=nullptr;}bool LinkQueue::isEmpty(){ return front==rear?true:false;}int LinkQueue::length(){ int cnt = 0; nodePtr t =front; while(t != rear){ ++cnt; t = t->next; } return cnt;}bool LinkQueue::getHead(Type &e){ if(isEmpty()) return false; e = front->next->data;}bool LinkQueue::push(Type &e){ nodePtr t = new node; t->data = e; t->next = nullptr; rear->next = t; rear = t;}bool LinkQueue::pop(Type &e){ if(isEmpty()) return false; nodePtr t = front->next; e = t->data; front->next=t->next; if(rear==t) rear =front; return true;}
- 主函数(main.cpp):
#include <iostream>#include "LinkQueue.h"using namespace std;int main(){ LinkQueue q; Type e=1; q.push(e); e=2; q.push(e); q.pop(e); cout<<e<<' '; e=3; q.push(e); e=4; q.push(e); q.pop(e); cout<<e<<' '; q.pop(e); cout<<e<<' '; q.pop(e); cout<<e<<' '; return 0;}
运行结果
应用
队列一般应用在计算过程按层次性顺序进行的场景,比如层次遍历树、调度算法等。具体将会在讲到树的时候提到。
阅读全文
0 0
- 链队列的C++实现及其应用
- 队列(Queue)的python实现及其应用
- 队列的基本操作实现及其应用
- 实验4:栈和队列的基本操作实现及其应用——链队列
- 实验4:栈和队列的基本操作实现及其应用之《链队列》
- 实验4:栈和队列的基本操作实现及其应用之《链队列》
- 实验4:栈和队列的基本操作实现及其应用之《链队列》
- 实验3:栈和队列的基本操作实现及其应用——顺序队列和链队列
- 队列及其c语言实现
- 队列及其c语言实现
- 优先队列的实现及其在哈夫曼编码中的应用
- 实验4:栈和队列的基本操作实现及其应用——循环队列
- 实验4:栈和队列的基本操作实现及其应用之《循环队列》
- 实验4:栈和队列的基本操作实现及其应用之《顺序队列》
- 实验4:栈和队列的基本操作实现及其应用之《顺序队列》
- 实验3:栈和队列的基本操作实现及其应用——顺序栈和链栈
- 循环队列的主要特点及其应用
- 数据结构 链队列的建立及其函数 C语言版
- idea默认文件编码格式设置
- python list排序的两种方法及实例讲解
- 深度学习batchsize,iteration,epoch的关系
- 关于uEditor,上传图片到指定主机(图片服务器)
- android viewpager和fragment
- 链队列的C++实现及其应用
- OC -基础(四) 学习中。。。
- PTA简单计算器
- 二分方法查询一个数的角标
- ThinkPHP框架短信接口
- os.path 模块
- 【DOS网络命令】-ftp的用法
- 关于字符串循环左移的若干解决方法
- LightOJ1282