#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;
}
用顺序表实现队列
最新推荐文章于 2021-08-14 20:20:01 发布