队列头文件(MyQueue.h)
#pragma
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_Tail;
};
队列的实现文件(MyQueue.cpp)
#include<iostream>
#include"MyQueue.h"
using namespace std;
MyQueue::MyQueue(int queueCapacity)
{
m_pQueue = new int[queueCapacity];
m_iQueueCapacity = queueCapacity;
ClearQueue();
}
MyQueue::~MyQueue()
{
delete[] m_pQueue;
m_pQueue = NULL;
}
void MyQueue::ClearQueue()
{
m_iQueueLen = 0;
m_iHead = 0;
m_Tail = 0;
}
bool MyQueue::QueueEmpty() const
{
return (m_iQueueLen == 0 ? true : false);
}
bool MyQueue::QueueFull() const
{
return m_iQueueCapacity == m_iQueueLen ? true : false;
}
int MyQueue::QueueLength() const
{
return m_iQueueLen;
}
bool MyQueue::EnQueue(int element)
{
if (QueueFull())
{
return false;
}
else
{
m_pQueue[m_Tail++] = element;
m_Tail = m_Tail % 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_iQueueCapacity;
m_iQueueLen--;
return true;
}
}
void MyQueue::QueueTraverse()
{
for (int i = m_iHead;i < m_iQueueLen+ m_iHead;i++)
{
m_pQueue[i%m_iQueueCapacity].printInfo();
}
}
测试函数
#include<iostream>
#include<stdlib.h>
#include"Queue.h"
using namespace std;
int main()
{
MyQueue *p= new MyQueue (4);
p->EnQueue(10);
p->EnQueue(12);
p->EnQueue(16);
p->EnQueue(18);
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();
cout << endl;
p->ClearQueue();
p->QueueTraverse();
p->EnQueue(20);
p->EnQueue(32);
cout << endl;
p->QueueTraverse();
delete p;
p = NULL;
system("pause");
return 0;
}