main文件:
#include <iostream>
#include "queue.h"
using namespace std;
int main()
{
queue q;
//创建循环顺序栈
q.create();
//入栈
q.push(1);
q.push(8);
q.push(5);
q.push(2);
q.push(6);
q.push(4);
//遍历
q.show();
//出队
q.pop();
q.pop();
q.pop();
//遍历
q.show();
//销毁
q.destroy();
return 0;
}
实现效果:
.h文件:
#ifndef QUEUE_H
#define QUEUE_H
#define MAX 20
typedef int datatype;
class queue
{
private:
datatype *data;
int front;
int tail;
public:
//创建
void create();
//判空
bool empty();
//判满
bool full();
//入队
void push(datatype e);
//出队
void pop();
//遍历
void show();
//销毁
void destroy();
};
#endif // QUEUE_H
.c文件:
#include <iostream>
#include "queue.h"
using namespace std;
//创建
void queue::create()
{
data = new datatype[MAX];
front = tail = 0;
}
//判空
bool queue::empty()
{
return front == tail;
}
//判满
bool queue::full()
{
return front == (tail+1)%MAX;
}
//入队
void queue::push(datatype e)
{
if(full())
{
cout<<"队已满,无法入队"<<endl;
return;
}
data[tail] = e;
tail = (tail+1)%MAX;
}
//出队
void queue::pop()
{
if(empty())
{
cout<<"队已空,无法出队"<<endl;
return;
}
front = (front+1)%MAX;
}
//遍历
void queue::show()
{
if(empty())
{
cout<<"队已空,无法遍历"<<endl;
return;
}
for(int i = front;i != tail;i = (i+1)%MAX)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
//销毁
void queue::destroy()
{
delete []data;
data = nullptr;
}
在判满与遍历的时候需要注意顺序队列的循环特征。