#ifndef MYQUEUE_H #define MYQUEUE_H class MyQueue { public: MyQueue(int queueCapacity); //InitQueu(&Q) 创建队列 virtual ~MyQueue(); //DestroyQueue(&Q) 销毁队列 void ClearQueue(); //ClearQueue(&Q) 清空队列 bool QueueEmpty() const; //QueueEmmpty(Q) 判空队列 bool QueueFull() const; //判满队列 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; //m_iHead = 0; //m_iTail = 0; //m_iQueueCapacity = 0; m_pQueue = new int[m_iQueueCapacity]; ClearQueue(); } MyQueue::~MyQueue() { delete []m_pQueue; m_pQueue = NULL; } void MyQueue::ClearQueue() { m_iHead = 0; m_iTail = 0; m_iQueueCapacity = 0; } bool MyQueue::QueueEmpty() const { if (m_iQueueLen == 0) { return true; } else { return false; } //return m_iQueueLen == 0 ? trur :false; } int MyQueue::QueueLength() const { return m_iQueueLen; } bool MyQueue::QueueFull() const { if (m_iQueueLen == m_iQueueCapacity) { return true; } else return false; } 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() { for (int i = m_iHead; i < m_iQueueLen + m_iHead; i++) { cout << m_pQueue[i%m_iQueueCapacity] << endl; } }
#include <stdlib.h>
#include "MyQueue.h"
#include <iostream>
using namespace std;
int main(void)
{
MyQueue *p = new MyQueue(10);
p->EnQueue(10);
p->EnQueue(12);
p->EnQueue(16);
p->EnQueue(18);
//p->EnQueue(20);
p->QueueTraverse();
int e = 0;
p->DeQueue(e);
cout << e << endl;
p->DeQueue(e);
cout << e << endl;
p->QueueTraverse();
p->ClearQueue();
p->QueueTraverse();
p->EnQueue(20);
p->EnQueue(30);
p->QueueTraverse();
delete p;
p = NULL;
system("pause");
return 0;
}
MinRam