Q:通过 数组 实现 队列(FIFO)功能
A:
MyQueue.h
#ifndef MYQUEUE_H
#define MYQUEUE_H
/*************************************/
/*环形队列实现 2017.03.01 by hyc */
/************************************/
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; //队尾
};
#endif
MyQueue.cpp
#include "MyQueue.h"
#include <iostream>
using namespace std;
/*************************************/
/*环形队列实现 2017.03.01 by hyc */
/************************************/
MyQueue::MyQueue(int queueCapacity)
{
m_iQueueCapacity = queueCapacity;
m_pQueue = new int[m_iQueueCapacity];
m_iHead = 0;
m_iTail = 0;
m_iQueueLen = 0;
}
MyQueue::~MyQueue()
{
delete[] m_pQueue;
m_pQueue = NULL;
}
void MyQueue::ClearQueue()
{
m_iHead = 0;
m_iTail = 0;
m_iQueueLen = 0;
}
bool MyQueue::QueueEmpty() const
{
return m_iQueueLen == 0 ? true : false;
}
bool MyQueue::QueueFull() const
{
return m_iQueueLen == m_iQueueCapacity ? true : false;
}
int MyQueue::QueueLength() const
{
return m_iQueueLen;
}
bool MyQueue::EnQueue(int element)
{
if (QueueFull()){
return false;
}
m_pQueue[m_iTail] = element;
m_iTail++;
m_iTail = m_iTail % m_iQueueCapacity;
m_iQueueLen++;
return true;
}
bool MyQueue::DeQueue(int &element)
{
if (QueueEmpty()){
return false;
}
element = m_pQueue[m_iHead];
m_iHead++;
m_iHead = m_iHead % m_iQueueCapacity;
m_iQueueLen--;
return true;
}
void MyQueue::QueueTraverse()
{
cout << endl;
for (int i = m_iHead; i < m_iHead + m_iQueueLen; i++){
cout << m_pQueue[i % m_iQueueCapacity] << endl;//我写错了
}
cout << endl;
}
demo.cpp:用于测试队列功能是否实现
#include "MyQueue.h"
#include <iostream>
using namespace std;
/*************************************/
/*环形队列实现 2017.03.01 by hyc */
/************************************/
int main(void)
{
MyQueue *p = new MyQueue(4);
p->EnQueue(1);
p->EnQueue(2);
p->EnQueue(3);
p->EnQueue(4);
p->EnQueue(5);
p->QueueTraverse();
int e = 0;
p->DeQueue(e);
p->QueueTraverse();
cout << e << endl;
p->DeQueue(e);
p->QueueTraverse();
cout << e << endl;
p->ClearQueue();
p->QueueTraverse();
p->EnQueue(10);
p->EnQueue(20);
p->QueueTraverse();
int j = 0;
j=p->QueueLength();
cout << j << endl;
delete p;
p = NULL;
system("pause");
return 0;
}
输出结果:
注意:本次练习只实现了简单的int类型的队列功能,可以使用模板类进一步实现其多类型支持。并且本程序有很多不完善的地方,如分配空间等的异常检测。