相比存储默认类型的循环队列,首先我们需要自定义存储的类。
自定义顾客类(Customer.h)
#pragma once
#include<string>
using namespace std;
class Customer
{
public:
Customer(string name="", int age=0);
void printInfo() const;
private:
string m_strName;
int m_iAge;
};
队列头文件(MyQueue.h)
#pragma
#include "Customer.h"
class MyQueue
{
public:
MyQueue(int queueCapacity);//InitQueue(&Q) 创建队列
virtual ~MyQueue(); //DestroyQueue(&Q)销毁队列
void ClearQueue(); //ClearQueue(&Q)清空队列
bool QueueEmpty() const; //QueueEmpty(Q) 判空
bool QueueFull() const; //判断队满操作
int QueueLength() const; //QueueLength(Q)队列长度
bool EnQueue(Customer element); //插入元素为自定义类型
bool DeQueue(Customer &element); //删除元素为自定义类型
void QueueTraverse(); //QueueTraverse(Q,visit())遍历队列
private:
Customer *m_pQueue;
int m_iQueueLen; //队列元素个数
int m_iQueueCapacity; //队列数组容量
int m_iHead; //对头
int m_Tail; //对尾
};
队列的实现文件(MyQueue.cpp)
#include<iostream>
#include"Queue.h"
#include"Customer.h"
using namespace std;
MyQueue::MyQueue(int queueCapacity)
{
m_pQueue = new Customer[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(Customer element)
{
if (QueueFull())
{
return false;
}
else
{
m_pQueue[m_Tail++] = element;
m_Tail = m_Tail % m_iQueueCapacity;
m_iQueueLen++;
return true;
}
}
bool MyQueue::DeQueue(Customer &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 cur(4);
Customer c1("jack", 10);
Customer c2("sva", 20);
Customer c3("greqrg", 30);
Customer c4("javfdck", 40);
cur.EnQueue(c1);
cur.EnQueue(c2);
cur.EnQueue(c3);
cur.EnQueue(c4);
cur.QueueTraverse();
cout << endl;
Customer c5;
cur.DeQueue(c5);
c5.printInfo();
Customer c6;
cur.DeQueue(c6);
c6.printInfo();
cout << endl;
cur.QueueTraverse();
cur.ClearQueue();
cout << endl;
Customer c7("vavdf", 90);
Customer c8("wefer", 40);
cur.EnQueue(c7);
cur.EnQueue(c8);
cur.QueueTraverse();
system("pause");
return 0;
}