代码示例:
#ifndef MYQUEUE_H
#define MYQUEUE_H
class MyQueue
{
public:
MyQueue(int queueCapacity);//InitQueue(&Q)创建队列
virtual ~MyQueue();//DestroyQueue(&Q)销毁队列
void ClearQueue();//ClearQueue(&Q)清空队列
bool QueueEmpty()const;//QueuEmpty(Q)判空队列
bool QueueFull()const;//QueueFull(Q)判满队列
int QueueLength()const;//QueueLength(Q)队列长度
bool EnQueue(int element);//EnQueue(&Q element)新元素入队
bool DeQueue(int &element);//DeQueue(&Q element)首元素出队
void QueueTraverse();//QueueTraverse(Q visit())遍历队列
private:
int *m_pQueue;//队列数组指针
int m_iQueueLen;//队列元素个数
int m_iQueueCapacity;//队列数组容量
int m_iHead;
int m_iTail;
};
#endif;
#include"MyQueue.h"
#include<iostream>
using namespace std;
MyQueue::MyQueue(int queueCapacity)
{
m_iQueueCapacity=queueCapacity;
ClearQueue();
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;
}
bool MyQueue::QueueEmpty()const
{
if(m_iQueueLen==0)
{
return true;
}
else
{
return 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;
}
else
{
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;
}
else
{
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;
}
#include<iostream>
#include<stdlib.h>
#include"MyQueue.h"
using namespace std;
/*
实现环形队列
*/
int main()
{
MyQueue *p=new MyQueue(4);
p->EnQueue(10);
p->EnQueue(12);
p->EnQueue(16);
p->EnQueue(20);
p->QueueTraverse();
int e=0;
p->DeQueue(e);
cout<<endl;
cout<<e<<endl;
p->DeQueue(e);
cout<<endl;
cout<<e<<endl;
cout<<endl;
p->QueueTraverse();
p->ClearQueue();
p->QueueTraverse();
p->EnQueue(22);
p->EnQueue(33);
p->QueueTraverse();
delete p;
p=NULL;
system("pause");
return 0;
}
打印结果: