手动封装一个循环顺序队列类(Queue)
私有成员属性:存放队列的数组、两个变量分别记录队头和队尾下标
公有成员函数: 入队(push( type value ))
出队(pop())
展示(show)
求队列长度(size()):要求时间复杂度在常量级别
判满( bool full())
判空(bool empty())
//head
#ifndef HEAD_H
#define HEAD_H
#include <iostream>
#define MAXSIZE 5
using namespace std;
typedef int datatype;
class Queue
{
private:
int front;
int rear;
datatype data[MAXSIZE];
public:
//构造函数初始化头尾指针
Queue()
{
front = rear = 0;
}
//入队
void push(datatype val);
//出队
void pop();
//展示
void show();
//队列长度
int size();
//判满
bool full();
//判空
bool empty();
};
#endif // HEAD_H
//function
#include"head.h"
//入队
void Queue::push(datatype val)
{
if(full())
{
cout << "队列已满" << endl;
return;
}
data[rear] = val;
rear = (rear + 1) % MAXSIZE; //队尾指针向后移动
}
//出队
void Queue::pop()
{
if(empty())
{
cout << "队列为空" << endl;
return;
}
cout << "出队元素:"<< data[front] << endl;
front = (front+1)%MAXSIZE;
}
//展示
void Queue::show()
{
if(empty())
{
cout<<"队列为空"<<endl;
return;
}
//遍历
for(int i=front; i!=rear; i=(i+1)%MAXSIZE)
{
cout<<data[i]<<" "<<endl;
}
}
//队列长度
int Queue::size()
{
return (rear - front + MAXSIZE) % MAXSIZE;
}
//判满
bool Queue::full()
{
if(front == (rear + 1)%MAXSIZE)
{
return true;
}
return false;
}
//判空
bool Queue::empty()
{
if(rear == front)
{
return true;
}
return false;
}
#include "head.h"
int main()
{
Queue queue;
//入队操作
queue.push(1);
queue.push(2);
queue.push(3);
queue.push(4);
queue.push(5);
queue.push(2);
cout <<"队列长度:" << queue.size() << endl;
//遍历
queue.show();
//出队列
queue.pop();
//遍历
queue.show();
cout <<"队列长度:" << queue.size() << endl;
return 0;
}