循环队列的顺序存储结构基本实现(C++)

队列的顺序存储结构和链表的顺序存储结构非常的相近。为了降低队列的输出时间复杂度,将队列设置为循环队列,基本原理“大话数据结构”讲的很清楚,这里列出接个关键点:

1、判断队列为空的条件
	front==rear   //其中front为指向头元素的下标,rear为指向尾元素的下标的下一位置
2、判断队列为满的条件
	(rear+1)%MAXSIZE   //其中MAXSIZE为允许队列的最大长度
	值得注意的是为了区分空和满,定义比队列预设长度小1为满
3、计算队列长度的关系式
	(rear-front+MAXSIZE)%MAXSIZE
	这样做的目的是在情况rear小于front时

函数说明

template<typename T>
class Queue
{
private:
	T data[MAXSIZE];   //定义队列最大长度
	int front;    //指向队列首元素
	int rear;    //指向队列尾元素的下一位置
public:
	Queue();   //构造函数
	bool isEmpty() const;   //判断队列是否为空
	bool isFull() const;   //判断队列是否为满
	bool EnQueue(T &e);   //将元素e插入队列
	T DeQueue();   //删除头元素并返回
	int Length() const;   //返回队列的长度
};

使用示例结果

Enter the arrival customer name:
bndrbsdf
There have 1 customers.

Enter the arrival customer name:
bsrtmndty
There have 2 customers.

Enter the arrival customer name:
bwsnety
There have 3 customers.

Enter the arrival customer name:
gbwerbted
There have 4 customers.

bndrbsdf leave, and 3 people remain.
bsrtmndty leave, and 2 people remain.
bwsnety leave, and 1 people remain.
gbwerbted leave, and 0 people remain.

头文件

#	pragma once
#ifndef QUEUEV2_H_
#define QUEUEV2_H_

#define MAXSIZE 5

template<typename T>
class Queue
{
private:
	T data[MAXSIZE];
	int front;
	int rear;
public:
	Queue();
	bool isEmpty() const;
	bool isFull() const;
	bool EnQueue(T &e);
	T DeQueue();
	int Length() const;
};

template<typename T>
Queue<T>::Queue()
{
	front = 0;
	rear = 0;
}

template<typename T>
bool Queue<T>::isEmpty() const
{
	return(front == rear);
}

template<typename T>
bool Queue<T>::isFull() const
{
	return((rear + 1) % MAXSIZE == front);
}

template<typename T>
bool Queue<T>::EnQueue(T &e)
{
	if (isFull()) {
		cout << "The queue is full!!!\n";
		return false;
	}
	else {
		data[rear] = e;
		rear = (rear + 1) % MAXSIZE;
		return true;
	}
}

template<typename T>
T Queue<T>::DeQueue()
{
	if (isEmpty()) {
		cout << "The queue is empty!!!\n";
		exit(EXIT_FAILURE);
	}
	else {
		T e = data[front];
		front = (front + 1) % MAXSIZE;
		return e;
	}
}

template<typename T>
int Queue<T>::Length() const
{
	return(rear - front + MAXSIZE) % MAXSIZE;
}

#endif // !QUEUEV2_H_

使用示例

#include<iostream>
#include<random>
#include<ctime>
#include<string>
#include"queuev2.h"

using namespace std;

void main()
{
	Queue<string> test;
	srand(time(0));
	while (!test.isFull()) {
		cout << "Enter the arrival customer name: \n";
		string name;
		getline(cin, name);
		test.EnQueue(name);
		cout << "There have " << test.Length() << " customers.\n\n";
	}
	while (!test.isEmpty()) {
		cout << test.DeQueue() << " leave, and ";
		cout << test.Length() << " people remain.\n";
	}
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值