1、作业要求
使用C++的类实现循环顺序队列。
2、实现过程
1)queue.h文件
#ifndef QUEUE_H
#define QUEUE_H
#define MAX 10
class Queue {
private:
int* data;
int front;
int tail;
public:
//初始化
void init();
//判空
bool queue_empty();
//入队
void queue_push(int e);
//遍历
void queue_show();
//出队
void queue_pop();
//队列长度
int queue_size();
//销毁
void queue_delete();
};
#endif // QUEUE_H
2)queue.cpp文件
#include <iostream>
#include <queue.h>
using namespace std;
//初始化
void Queue::init() {
data = new int[MAX];
front = 0;
tail = 0;
}
//判空
bool Queue::queue_empty() {
return front==tail;
}
//入队
void Queue::queue_push(int e) {
data[tail] = e;
cout << data[tail] << " 入队成功" << endl;
tail = (tail+1)%MAX;
}
//遍历
void Queue::queue_show() {
if(queue_empty()) {
cout << "遍历失败" << endl;
}
for(int i=front; i!=tail; i=(i+1)%MAX) {
cout << data[i] << " ";
}
cout << endl;
}
//出队
void Queue::queue_pop() {
if(queue_empty()) {
cout << "出队失败" << endl;
}
cout << data[front] << " 出队成功" << endl;
front = (front+1) % MAX;
}
//队列长度
int Queue::queue_size() {
if(queue_empty()) {
cout << "长度为0" << endl;
}
return (tail+MAX-front)%MAX;
}
//销毁
void Queue::queue_delete() {
delete []data;
data = nullptr;
cout << "销毁成功" << endl;
}
3)main.cpp文件
#include <iostream>
#include <queue.h>
using namespace std;
int main()
{
Queue q1;
//初始化
q1.init();
//入队
q1.queue_push(5);
q1.queue_push(9);
q1.queue_push(7);
q1.queue_push(6);
q1.queue_push(2);
//遍历
q1.queue_show();
//出队
q1.queue_pop();
q1.queue_pop();
q1.queue_pop();
//遍历
q1.queue_show();
//队列长度
cout << "队列长度为:" << q1.queue_size() << endl;
//销毁
q1.queue_delete();
return 0;
}
3、效果截图