概述
代码:
#include <iostream>
#define MAX 5
using namespace std;
class Queue{
private:
int a[MAX];
int Front;
int Rear;
public:
Queue();
bool IsEmpty();
bool IsFull();
bool EnQueue(int data);
int DeQueue(); //返回出队列的值
bool ergodic(); //遍历
};
/******初始化******/
Queue::Queue(){
this->Front = 0;
this->Rear = 0;
}
bool Queue::IsEmpty(){
if(this->Front==this->Rear)
return true;
else
return false;
}
bool Queue::IsFull(){
if((this->Rear+1)%MAX==this->Front)
return true;
else
return false;
}
bool Queue::EnQueue(int data){
if(IsFull())
return false;
this->a[this->Rear] = data;
this->Rear = (this->Rear+1)%MAX;
return true;
}
int Queue::DeQueue(){
if(IsEmpty())
return false;
int data = this->a[this->Front];
this->Front = (this->Front+1)%MAX;
return data;
}
bool Queue::ergodic(){
if(IsEmpty())
return false;
if(this->Rear>this->Front){
for(int i=this->Front;i<this->Rear;i++)
cout<<this->a[i]<<" ";
}
if(this->Rear<this->Front){
for(int i=this->Front;i<MAX;i++)
cout<<this->a[i]<<" ";
for(int i=0;i<this->Rear;i++)
cout<<this->a[i]<<" ";
}
return true;
}
int main()
{
Queue q;
q.EnQueue(1);
q.EnQueue(2);
q.EnQueue(3);
q.EnQueue(4);
int a = q.DeQueue();
cout << a << endl;
q.EnQueue(5);
q.ergodic();
return 0;
}
测试:
加上template后可实现对任意类型的操作
代码:
#include <iostream>
#define MAX 5
using namespace std;
template <typename T>
class Queue{
private:
T a[MAX];
int Front;
int Rear;
public:
Queue();
bool IsEmpty();
bool IsFull();
bool EnQueue(T data);
T DeQueue(); //返回出队列的值
bool ergodic(); //遍历
};
/******初始化******/
template <typename T>
Queue<T>::Queue(){
this->Front = 0;
this->Rear = 0;
}
template <typename T>
bool Queue<T>::IsEmpty(){
if(this->Front==this->Rear)
return true;
else
return false;
}
template <typename T>
bool Queue<T>::IsFull(){
if((this->Rear+1)%MAX==this->Front)
return true;
else
return false;
}
template <typename T>
bool Queue<T>::EnQueue(T data){
if(IsFull())
return false;
this->a[this->Rear] = data;
this->Rear = (this->Rear+1)%MAX;
return true;
}
template <typename T>
T Queue<T>::DeQueue(){
if(IsEmpty())
return false;
T data = this->a[this->Front];
this->Front = (this->Front+1)%MAX;
return data;
}
template <typename T>
bool Queue<T>::ergodic(){
if(IsEmpty())
return false;
if(this->Rear>this->Front){
for(int i=this->Front;i<this->Rear;i++)
cout<<this->a[i]<<" ";
}
if(this->Rear<this->Front){
for(int i=this->Front;i<MAX;i++)
cout<<this->a[i]<<" ";
for(int i=0;i<this->Rear;i++)
cout<<this->a[i]<<" ";
}
return true;
}
int main()
{
Queue<float> q;
q.EnQueue(1);
q.EnQueue(2.3);
q.EnQueue(3);
q.EnQueue(4.55);
float a = q.DeQueue();
cout << a << endl;
q.EnQueue(5);
q.ergodic();
return 0;
}
测试:
最后
以上就是深情大树为你收集整理的《面试准备》c/c++ 数组实现循环queue的全部内容,希望文章能够帮你解决《面试准备》c/c++ 数组实现循环queue所遇到的程序开发问题。
如果觉得靠谱客网站的内容还不错,欢迎将靠谱客网站推荐给程序员好友。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复