C++实现环形队列
#include <cstdio>
#include <algorithm>
#include <iostream>
#include <string>
using namespace std;
class Customer
{
public:
Customer(string name = "", int age = 0)
{
m_strName = name;
m_iAge = age;
}
~Customer()
{
}
void printInfo() const
{
cout << endl;
cout << "xingming :" << m_strName << endl;
cout << "nianling :" << m_iAge << endl;
}
private:
string m_strName;
int m_iAge;
};
class MyQueue
{
public:
MyQueue(int queueCapacity)
{
m_iQueueCapacity = queueCapacity;
m_pQueue = new Customer[m_iQueueCapacity];
ClearQueue();
}
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;
}
}
bool QueueFull() const
{
if (m_iQueuelen == m_iQueueCapacity)
{
return true;
}
else
{
return false;
}
}
int QueueLenth() const
{
return m_iQueuelen;
}
bool EnQueue(Customer element)
{
if (QueueFull())
{
return false;
}
else
{
m_pQueue[m_iTail] = element;
m_iTail++;
m_iTail = m_iTail % m_iQueueCapacity;
m_iQueuelen++;
return true;
}
}
bool DeQueue(Customer &element)
{
if (QueueEmpty())
{
return false;
}
else
{
element = m_pQueue[m_iHead];
m_iHead++;
m_iHead = m_iHead % m_iQueueCapacity;
m_iQueuelen--;
return true;
}
}
void QueueTraverse()
{
for (size_t i = m_iHead; i < m_iQueuelen + m_iHead; i++)
{
m_pQueue[i%m_iQueueCapacity].printInfo();
cout << "qian mian hai you " << (i - m_iHead) << "ren" << endl;
}
}
private:
Customer *m_pQueue;
int m_iQueuelen;
int m_iQueueCapacity;
int m_iHead;
int m_iTail;
};
int main()
{
MyQueue *p = new MyQueue(4);
Customer c1("xiaoming", 12);
Customer c2("xinasfmd", 32);
Customer c3("xinfsawe", 23);
p->EnQueue(c1);
p->EnQueue(c2);
p->EnQueue(c3);
p->QueueTraverse();
Customer c4("", 0);
p->DeQueue(c4);
c4.printInfo();
p->QueueTraverse();
delete[]p;
p = NULL;
system("pause");
return 0;
}