队列的特点就是从尾部进队列,从头部出队列,所以可以有两个指针,一个指向头部,一个指向尾部。然后用一个变量记录队列的目前长度,一个变量表示队列的最大长度,以此来判断是否为空,是否为满。然后设一个数组,来存放队列的值,数组大小为最大长度(动态分配,因此设一个指向数组的指针)
Function:
Struct QueueR
{
int rear;
int front;
int* Array;
int Size;
int Capacity;
} ; //假设存放的都是int类型数据
typedef struct QueueR* Queue;
Queue CreateQueue(int Maxsize) ;
void MakeEmpty(Queue Q);
int IsEmpty(Queue Q);
int IsFull(Queue Q);
void EnQueue(int x,Queue Q);
void DeQueue(Queue Q);
int Front(Queue Q);
void DisposeQueue(Queue Q);
int FrontAndDequeue(Queue Q);
//创建队列
首先明确何时为空队列(因为创建队列一开始就是空队列),当front>rear的时候就是空队列。又因为进入队列的时候,rear先++,然后再往相关位置插入元素,所以设置front=0,rear=-1.
Queue CreateQueue(int Qsize)
{
Queue Q = new struct QueueR;
Q->Capacity = Qsize;
Q->front = 0;
Q->rear = -1;
Q->Size = 0;
Q->Arr = new int[Qsize];
return Q;
}
//MakeEmpty
void MakeEmpty(Queue Q)
{
Q->front = 0;
Q->rear = -1;
Q->Size = 0;
}
//IsEmpty&& IsFull
int IsEmpty(Queue Q)
{
return Q->Size == 0;
}
int IsFull(Queue Q)
{
return Q->Size == Q->Capacity;
}
//进出队列
进队列:先检查是否满,size++ 、 rear- - 然后判断rear是否到达数组尾部,如果到达尾部则rear设为0,然后插入元素。
出队列:先检查是否空,size- -、front++,然后判断front是否到达数组尾部,如果是则设置为0
void Enqueue(int x, Queue Q)
{
if (IsFull(Q))
{
cerr << "No space";
return;
}
Q->Size++;
Q->rear++;
if (Q->rear == Q->Capacity)
Q->rear = 0;
Q->Arr[Q->rear] = x;
}
void Dequeue(Queue Q)
{
if (IsEmpty(Q))
{
cerr << "empty queue";
return;
}
Q->front++;
Q->Size--;
if (Q->front == Q->Capacity)
Q->front = 0;
}
//销毁
切记delete两个
void DisposeQueue(Queue Q)
{
delete Q->Array;
delete Q;
}
//出队&&出队元素
检查是否为空,size–,int temp=front的元素,然后front-- ,检查是否数组尾部,是则设为0
int FrontAndDequeue(Queue Q)
{
if (IsEmpty(Q))
{
cerr << "queue empty";
exit(EXIT_FAILURE);
}
int temp;
temp = Q->Arr[Q->front++];
if (Q->front == Q->Capacity)
Q->front = 0;
return temp;
}
//简单进队和出队
#include"queue.h"
#include<iostream>
using namespace std;
int main()
{
Queue q1;
q1 = CreateQueue(10);
MakeEmpty(q1);
for (int i = 0; i < 10; i++)
{
Enqueue(i, q1);
cout << q1->Arr[q1->rear] << " has enqueued\n";
}
for (int i = 0; i < 10; i++)
{
cout << FrontAndDequeue(q1) << " has dequeued\n";
}
DisposeQueue(q1);
return 0;
}