环形队列

#pragma once

//这里实现的是环形队列
class MyQueue
{
public:
    MyQueue(int queueCapacity); //创建队列
    virtual ~MyQueue();         //销毁队列
    void ClearQueue();          //清空队列
    bool QueueEmpty()const;     //判断队列
    bool QueueFull()const;     //队列判满
    int QueueLength()const;     //队列长度
    bool EnQueue(int element);  //新元素入队
    bool DeQueue(int &element); //首元素出队
    void QueueTraverse();       //遍历队列
private:
    int *m_pQueue;         //队列数组指针
    int m_iQueueLen;       //队列元素个数
    int m_iQueueCapacity;  //队列数组容量

    int m_iHead;  //队头
    int m_iTail;  //队尾



};

 

#include"MyQueue.h"
#include<iostream>
using namespace std;
MyQueue::MyQueue(int queueCapacity)
{
    //用户传入队列大小queueCapacity,赋值给成员变量m_iQueueCapacity
    m_iQueueCapacity = queueCapacity;

    //初始化队头队尾
    m_iHead = 0;
    m_iTail = 0;
    //初始化元素个数为0
    m_iQueueLen = 0;

    //申请内存
    m_pQueue = new int[m_iQueueCapacity];

}
MyQueue::~MyQueue() 
{

    delete[]m_pQueue;
    m_pQueue = NULL;
}
void MyQueue::ClearQueue()          //清空队列
{
    //队头队尾置零
    m_iHead = 0;
    m_iTail = 0;
    //元素个数置零
    m_iQueueLen = 0;
    cout << "清空成功!" << endl;
}
bool MyQueue::QueueEmpty()const    //队列判空
{
    if (m_iQueueLen == 0)
    {
        cout << "队列为空!" << endl;
        return true;
    }
    else
    {
        return false;
    }
}
bool MyQueue::QueueFull()const    //队列判满
{
    if (m_iQueueLen == m_iQueueCapacity)
    {
        cout << "队列已满!" << endl;
        return true;
    }
    else
    {
        return false;
    }
}
int MyQueue::QueueLength()const    //队列长度
{

    return m_iQueueLen;

}
bool MyQueue::EnQueue(int element)  //新元素入队
{
    if (QueueFull() == true)
    {
        return false;
    }
    else
    {
        //入队
        m_pQueue[m_iTail]= element;
        //队尾移动
        m_iTail++;
        m_iTail = m_iTail%m_iQueueCapacity;
        
        m_iQueueLen++;
        cout << element << "入队成功!" << endl;
        return true;
    }

}
bool MyQueue::DeQueue(int &element) //首元素出队
{
    if(QueueEmpty()==true)
    {
        return false;
    }
    else
    {
        //出队
        element = m_pQueue[m_iHead];
        m_iHead++;
        m_iHead = m_iHead%m_iQueueCapacity;
        m_iQueueLen--;
        cout << element << "出队成功!" << endl;
        return true;
    }
}
void MyQueue::QueueTraverse()      //遍历队列
{
    cout << "遍历结果:" << endl;
    for (int i = m_iHead;i < m_iQueueLen+ m_iHead;i++)
    {

        cout << m_pQueue[i%m_iQueueCapacity] << endl;
        

    }
    cout << "遍历成功!" << endl;

}

 

#include<iostream>
using namespace std;
#include"MyQueue.h"


int main()
{


    int a= 0;

    MyQueue *p = new MyQueue(4);

    p->EnQueue(10);
    p->EnQueue(12);
    p->EnQueue(13);
    p->EnQueue(14);



    p->DeQueue(a);
    cout << "出队" << a << endl;
    p->EnQueue(18);

    p->DeQueue(a);
    cout <<"出队"<< a << endl;

    p->EnQueue(17);
    p->QueueTraverse();

    delete p;
    p = NULL;

    getchar();
    return 0;

}

 

上一篇:21 循环队列


下一篇:第七节 线程队列