循环队列的插入与删除操作(C++)

记录一下C++实现循环队列;

#include<iostream>
using namespace std;

class queue {
public:
	queue(int max) {
		front = 0;
		rear = 0;
		maxlen = max;
		myqueue = new int[maxlen];
		num = 0;
	}
	~queue()
	{
		delete[]myqueue;
	}
	bool que_empty();     //判断队空;
	bool que_full();      //判断队满;
	void in(int x);       //入队;
	void out();           //出队;
	int length() const;   //队列长度;
	void print_que();     //打印队列;

private:
	int front;
	int rear;
	int maxlen;
	int *myqueue;
	int num;
};

bool queue::que_empty()
{
	return num == 0 ? true : false;
}
bool queue::que_full()
{
	return num == maxlen ? true : false;
}
void queue::in(int x)
{
	if (que_full())
		cout << "插入失败,已满" << endl;
	else
	{
		myqueue[rear%maxlen] = x;
		rear = (rear + 1) % maxlen;
		num++;
	}
}
void queue::out()
{
	if (que_empty())
		cout << "删除失败,已空" << endl;
	else
	{
		front = (front + 1) % maxlen;
		num--;
	}
}

int queue::length() const
{
	return num;
}

void queue::print_que()
{
	for (int i = front; i < num + front; i++)
	{
		cout << myqueue[i%maxlen] << endl;
	}
}
int main()
{
	queue *p = new queue(5);
	p->in(2);
	p->in(5);
	p->in(10);
	p->in(15);
	p->in(20);
	//p->in(25);
	p->out();
	p->out();
	cout<<"队列长度是: "<<p->length()<<endl;
	p->print_que();
	system("pause");
	return 0;
}

阅读更多
版权声明: https://blog.csdn.net/qq_39871576/article/details/79975109
文章标签: 循环队列
个人分类: 数据结构
想对作者说点什么? 我来说一句

没有更多推荐了,返回首页

关闭
关闭
关闭