循环队列实例C++代码实现

队列是一种先进先出的线性表,允许插入的一端称为队尾,允许删除的一端称为队头。头尾相接的顺序存储结构称为循环队列。

Circle_Queue.h

#pragma once
#define Queue_Datatype int
#define Init_QueueData 99
#define Queue_Space 10

class MyQueue
{
public:
	MyQueue();
	~MyQueue();

	void Init_Queue();		//	初始化队列
	void Destory_Queue();	//	摧毁队列
	void Clear_Queue();		//	清空队列

	bool Queue_Empty();		//	是否为空队列
	int Queue_Size();		//  队列长度

	int Queue_Head();		//	获取队头数据
	bool Queue_Push(Queue_Datatype x);		//	入队
	bool Queue_Pop();		//	出队

	void Print_Queue();		//  遍历队列

private:
	int front;				//	队头
	int rear;				//	队尾
	bool Is_Empty;
	Queue_Datatype* base;	// 指向连续存储空间
};

Circle_Queue.cpp

#include "Circle_Queue.h"
#include <iostream>

MyQueue::MyQueue()
{
	Init_Queue();
}

MyQueue::~MyQueue()
{
	Destory_Queue();
}


void MyQueue::Init_Queue()
{
	base = new(std::nothrow) Queue_Datatype[Queue_Space];
	if (!base)
		std::exit(1);
	front = 0;
	rear = 0;
	Is_Empty = true;
}

void MyQueue::Destory_Queue()
{
	delete[]base;
}

void MyQueue::Clear_Queue()
{
	front = 1;
	rear = 1;
}

bool MyQueue::Queue_Empty()
{
	return Is_Empty;
}

int MyQueue::Queue_Size()
{
	return (rear - front + Queue_Space) % Queue_Space;
}

int MyQueue::Queue_Head()
{
	if (Is_Empty)
		std::cout << "队列为空" << std::endl;
	else
	{
		Queue_Datatype value = base[front + 1];
		return value;
	}
}

bool MyQueue::Queue_Push(Queue_Datatype x)
{
	if (!Is_Empty && rear == front)
		return false;
	
	rear = (rear + 1) % Queue_Space;
	base[rear] = x;
	Is_Empty = false;
}

bool MyQueue::Queue_Pop()
{
	if (Is_Empty)
		std::cout << "队列为空" << std::endl;
	return false;

	front = (front + 1) % Queue_Space;
	if (front == rear)
		Is_Empty = true;

	return true;
}

void MyQueue::Print_Queue()
{
	if (Is_Empty)
		std::cout << "队列为空" << std::endl;
	int temp = (front + 1) % Queue_Space;

	while (temp!=rear)
	{
		std::cout << base[temp] << std::endl;
		temp = (temp + 1) % Queue_Space;
	}
	std::cout<<  base[temp] << std::endl;
}

test.cpp

#include "Circle_Queue.h"
#include <iostream>

int main()
{

	MyQueue a;
	for (int i = 0; i < 5; i++) 
	{
		a.Queue_Push(i);
	}
	std::cout << "队列长度: " << a.Queue_Size() << std::endl;
	a.Print_Queue();

	a.Queue_Push(10);
	std::cout << "插入元素后的队列遍历: " << std::endl;
	a.Print_Queue();

	std::cout << "队头元素: " << a.Queue_Head() << std::endl;
	system("pause");
	return 0;
}

在这里插入图片描述

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值