Queue.h:
#include "iostream"
//using namespace std;
#ifndef QUEUE
#define QUEUE
const int QUEUE_CAPACITY =128;
typedef int QueueElement;
class Queue{
private:
int myFront;
int myBack;
QueueElement myArray[QUEUE_CAPACITY];
public:
Queue();
bool empty() const;
void enqueue(const QueueElement &value);
void display() const;
QueueElement front() const;
void dequeue();
};
#endif
Queue.cpp:
#include"iostream"
using namespace std;
#include "Queue.h"
Queue::Queue() //构造函数
:myFront(0), myBack(0)
{}
bool Queue::empty() const{
return (myFront==myBack); //判断队列是否为空
}
void Queue::enqueue(const QueueElement &value){ //从队尾插入元素(入队)
int newBack=(myBack+1)%QUEUE_CAPACITY; //newBack不为0则表示队列没满
if (newBack!=myFront){ //队列没满
myArray[myBack]=value;;
myBack=newBack;
}
else{
cout<<"/n";
exit(1);
}
}
void Queue::display() const{
for(int i=myFront; i!=myBack; i=(i+1)%QUEUE_CAPACITY){
cout<<myArray[i]<<" ";
cout<<endl;
}
}
QueueElement Queue::front() const{
if(!empty())
return (myArray[myFront]);
else
{
cerr<<"Queue is empty----returing garbage value--/n";
QueueElement garbage;
return garbage;
}
}
void Queue::dequeue(){ //从队头删除一个元素(出队)
if(!empty())
myFront=(myFront+1)%QUEUE_CAPACITY; //myFront后移一位
else
cerr<<"Queue is empty! can't remove a value!/n";
}
int main(){
int num;
Queue q;
int m,n;
/* 入队10个数 */
cout<<"请输入10个数:"<<endl;
for(int i=0; i<10;i++){
cin>>num;
q.enqueue(num);
}
/* 输出此时队列的元素 */
cout << "队列所有元素:" << endl;
q.display();
/* 出队 */
cout<<"请输入出队元素的个数:";
cin>>m;
for (int i=0; i<m; i++ ){ //出5个元素
q.dequeue();
}
cout << endl;
/* 输出此时队列的元素 */
cout << "出队后队列所有元素:" << endl;
q.display();
cout<<endl;
/* 再入队 */
cout<<"请输入入队元素的个数:";
cin>>n;
cout<<"请输入"<<n<<"个数:"<<endl;
for (int i= 0;i<n; i++ ){
cin>>num;
q.enqueue(num);
}
/* 输出此时队列的元素 */
cout << "入队后队列所有元素:" << endl;
q.display();
cout<<endl;
system("pause");
return 0;
}