C++数据结构探险——队列篇

数据结构的原理

队列:先进先出(FIFO:first in first out)

普通队列:

环形队列:

//MyQUeue.h

#ifndef MYQUEUE.H
#define MYQUEUE.H
class MyQueue
{
public:
   MyQueue(int queueCapacity);//InitQueue(&Q)创建队列——>C 语言:创建队列,必须有指针Q指向队列,即队列分配内存
   virtual ~MyQueue();// DestroyQueue(&Q)销毁队列「不仅销毁队列,还销毁内存」—>虚函数一般和析构函数一起使用,节约时间和系统性能
   void ClearQueue();//ClearQueue(&Q)清空队列
   bool QueueEmpty() const;//QueueEmpty(Q)判空队列
   int QueueLength() const;//QueueLength(Q)队列长度
   bool EnQueue(int element);//EnQueue(&Q element)新元素ru队
   bool DeQueue)(int &element);//首元素出队
   void QueueTraverse();//QuemeTraverse(Q visit)遍历队列
private:————>C++ 
   int *m_pQueue;          //队列数组指针(指针指向数组队列)
   int m_iQueueLen;        //队列元素个数
   int m_iQueueCapacity;   //队列数组容量
   int m_Head;             //环形队列的头
   int m_iTail;            //环形队列的尾



#endif
//MyQueue.cpp
#include "MyQueue.h"
#include <iostream>
using  namespace std;
//创建队列
MyQueue::MyQueue(int queueCapacity)
{
   m_iQueueCapacity = queueCapacity; //
   m_pQueue = new int [m_iQueueCapacity];
   ClearQueue(); 
     //m_iHead = 0;//环形队列的头
     //m_iTail = 0;//环形队列的尾
     //m_iQueuelen = 0;//环形队列的元素个数(长度)
     //m_pQueue = new int[m_QueueCapacity];//环形队列的初始化
}
virtual ~MyQueue()
{
   delete[]m_pQueue;//内存回收,销毁数组
   m_pQueue = NULL;//将指针指向安全状态
}
void ClearQueue()  ————>恢复到初始状态,内存都还保存着,元素都不在了,队头和队尾恢复初始值
{
   m_iHead = 0;
   m_iTail = 0;
   m_iQueueLen = 0;


}

bool QueueEmpty() const
{
   if(m_iQueueLen == 0)
   {
       return true;
   }
   else
   {
       return false;
   }
//retun m_iQueueLen == 0?true:false
}


int QueueLength() const
{
   return m_iQueueLen;
}

//对列判满
bool MyQueue::QueueFull() const
{
   if (m_iQueueLen == m_iQueuecapacity)
   {
        return true;
   }
        return false;
}
//新元素入队
bool EnQueue(int element)
{
   if(QueueFull())
   {
        return false;
   }
   else
   {
        m_pQueue[m_iTail] = element;
        m_iTail ++;
        return true;
   }
}
// 新元素入队
bool MyQueue::EnQUeue(int element)
{
   if(QueueFull())
   {
       return false;
   }
   else
   {
       m_pQueue[m_iTail] = element;
       m_iTail ++;
       m_iTail = m_iTail % m_iQueueCapacity;
       m_iQueueLen ++;
       return true;
    }
}
//遍历函数
void MyQueue::QueueTraverse()
{
   for(int i = m_iHead; i<m_iQueueLen ; i++)
   {
       cout <<m_PQueue[i%m_QueueLen]<<endl;
   }
}

以C++完整的编写各种数据结构

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 本文主要讲解了队列的定义和队列主要功能实现的算法。最后会列举一些队列在程序设计当中常见的应用实例!相信了解了队列对...
    xiaoyouPrince阅读 1,122评论 0 0
  • 本文内容取自于小甲鱼的数据结构与算法。http://www.jianshu.com/p/230e6fde9c75 ...
    阿阿阿阿毛阅读 2,946评论 0 7
  • Android跨进程通信IPC整体内容如下 1、Android跨进程通信IPC之1——Linux基础2、Andro...
    隔壁老李头阅读 15,773评论 19 113
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,080评论 19 139
  • 今天相当不爽~~ 早起时不穿袜子,磨蹭着不肯洗脸刷牙,吃饭是吃几口就完,饭后拿出她爸买的零食来吃。我真是没耐心了,...
    圈_圈_阅读 160评论 0 0