作业需求:
封装一个循环顺序队列,并封装其相应的操作:判空、入队列、出队、遍历队、求队列长度、销毁
实现过程:
头文件:
#ifndef WORK02_H
#define WORK02_H
#include <iostream>
using namespace std;
class sequeue
{
int *data;
int front;
int tail;
public:
int size;
void init();
int empty();
int full();
void push(int e);
void show();
void pop();
int get_size();
void free();
};
#endif // WORK02_H
源文件:
#include <iostream>
#include<work02.h>
void sequeue::init()
{
data= new int [size];
front =0;
tail =0;
}
int sequeue::empty()
{
return front==tail;
}
int sequeue:: full()
{
return (tail+1)%size == front;
}
void sequeue::push(int e)
{
if(full())
{
cout<<"入队失败"<<endl;
return;
}
data[tail]=e;
tail=(tail+1)%size;
cout<<e<<" 入队成功"<<endl;
}
void sequeue::show()
{
if(empty())
{
cout<<"遍历失败"<<endl;
return;
}
cout<<"队伍中从对头到队尾元素分别是"<<endl;
for(int i=front;i!=tail;i=(i+1)%size)
{
cout<<data[i]<<" ";
}
cout<<endl;
}
void sequeue:: pop()
{
if(empty())
{
cout<<"出队失败"<<endl;
}
cout<<data[front]<<"出队成功"<<endl;
front=(front+1)%size;
}
int sequeue::get_size()
{
return (tail+size-front)%size;
}
void sequeue::free()
{
delete []data;
data=nullptr;
cout<<"销毁成功"<<endl;
}
测试文件:
#include <iostream>
#include<work02.h>
using namespace std;
int main()
{
sequeue p;
p.size=8;
p.init();
p.push(14);
p.push(58);
p.push(13);
p.push(9);
p.show();
p.pop();
p.show();
cout<<p.get_size()<<endl;
p.free();
return 0;
}
作业结果:
![](https://i-blog.csdnimg.cn/blog_migrate/dbbdc116746f6479263076b3d6d39593.png)