用顺序表实现队列

#include<iostream>
#include<cstdlib> 
#include<ctime>
using namespace std;
const int MaxElements = 5;

struct QueueRecord;
typedef QueueRecord* Queue;

struct QueueRecord {
	int capacity;//队列最大固定总量
	int front;//队列头部
	int rear;//队列尾部
	int size;//队列当前数据总量
	int array[MaxElements];//数据存储
};

//判断队列是否为空
int isEmpty(Queue q)
{
	return q->size == 0;
}

//判断队列是否已满
int isFull(Queue q)
{
	return q->size == q->capacity;
}

//创建队列
Queue CreateQueue(int MaxElements)
{
	Queue q = (QueueRecord*)malloc(sizeof(struct QueueRecord));
	if (q == NULL)
	{
		cout << "分配内存失败!" << endl;
		return q;
	}
	else
	{
		q->capacity = MaxElements;
		q->front = 0;
		q->rear = 0;
		q->size = 0;
		//memset(q->array, 0, sizeof(int) * MaxElements);
		/*for (int i = 0; i < q->capacity; i++)
		{
			q->array[i] = 0;
		}*/
		return q;
	}
}

//删除队列
void DisposeQueue(Queue& q)
{
	q->capacity = 0;
	q->front = 0;
	q->rear = 0;
	q->size = 0;
}

//置空队列
void MakeEmpty(Queue& q)
{
	q->front = 0;
	q->rear = 0;
	q->size = 0;
}

//将数据输入到队列当中
int Enqueue(int x, Queue& q)
{
	//如果队列已满
	if (isFull(q))
	{
		cout << "队列满,无法输入!" << endl;
		return -1;
	}
	else
	{
		if (q->size == 0)
		{
			q->array[0] = x;
		}
		q->size++;
		q->rear = (q->rear + 1) % q->capacity;
		q->array[q->rear] = x;
		return 0;
	}
}

//将数据弹出队列
int Dequeue(int& x, Queue q)
{
	if (isEmpty(q))
	{
		cout << "队列空,无法弹出!" << endl;
		return -1;
	}
	else
	{
		q->size--;
		x = q->array[q->front];//将首位数据传给x,类比弹出
		q->front = (q->front + 1) % q->capacity;
		return 0;
	}
}

//输出队列头部数据
void Front(Queue& q)
{
	cout << q->array[q->front] << endl;
}

//输出队列头部数据后弹出头部数据
int FrontAndDequeue(Queue& q)
{
	int x;//将删除的数据赋值给x
	Front(q);
	Dequeue(x,q);
	return x;
}

//显示队列中的数据
void ShowQueue(Queue& q)
{
	for (int i = q->front; i <= q->rear; i++)
	{
		cout << q->array[i] << " ";
	}
	cout << endl;
}

int main()
{
	srand(time(0));
	//const int MaxElements = 5;
	Queue q;
	q = CreateQueue(MaxElements);
	cout << "————————————测试输入——————————" << endl;
	for (int i = 0; i < MaxElements - 1 ; i++)
	{
		int tmp = rand() % 100;//将随机数输入到队列当中
		Enqueue(tmp, q);
	}
	ShowQueue(q);

	cout << "————————————测试输出——————————" << endl;
	for (int i = 0; i < MaxElements - 2; i++)
	{
		int tmp;
		Dequeue(tmp, q);
	}
	ShowQueue(q);

	cout << "————————————测试输出队列头部——————————" << endl;
	Front(q);

	return 0;
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值