分为三个文件,分别为头文件,实现文件,测试文件。
//约定初始化时rear与front均为0,元素增加一个时,rear++,减少一个是front++
//在结构体中添加变量length,以length = 0表示队列为空
//引入辅助函数MyAdd()以处理下标循环的问题
头文件:
#ifndef MYQUEUE_H_
#define MYQUEUE_H_
#define QUEUEMAXSIZE 100 //队列数组容量 下标从0-99
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
struct MyQueue;
typedef struct MyQueue * Queue;
typedef int ElementType;
int MyAdd(int number); // 内联函数,用于对组下标越界后的处理,达到下标循环的目的
Queue InitQueue(void);//构造一个空队列
bool QueueEmpty(Queue Q);//队列Q是否为空,空返回True
void DestoryQueue(Queue Q); //从内存中销毁(删除)队列Q
void ClearQueue(Queue Q); //清空队列Q
int QueueLength(Queue Q);//返回队列中元素个数
ElementType GetHead(Queue Q);//返回队列头元素
void OutQueue(Queue Q);//出队
void EnQueue(ElementType E, Queue Q);//入队,从队尾插入
#endif
实现文件:
#include "myqueue.h"
struct MyQueue
{
ElementType * Array; //数组指针
int front; //队头下标
int rear; //队尾下标
int maxsize; //数组容量,用以判断数组是否满
int length; //队长,即队中元素个数
};
int MyAdd(int number) //某种意义上类似于自定义++运算符
{
if(number == QUEUEMAXSIZE - 1)
return 0;
else
return number + 1;
}
Queue InitQueue(void)
{
Queue Q;
Q = (Queue)malloc(sizeof(struct MyQueue));
if(Q == NULL)
printf("Out Of Space!\n");
Q -> Array = (ElementType *)malloc(sizeof(ElementType) * QUEUEMAXSIZE);
if(Q -> Array == NULL)
printf("Out Of Space!\n");
Q -> front = 0;
Q -> rear = 0;
Q -> length = 0;
Q -> maxsize = QUEUEMAXSIZE;
return Q;
}
bool QueueEmpty(Queue Q)
{
if(Q -> length == 0)
return true;
return false;
}
void DestoryQueue(Queue Q)
{
free(Q -> Array);
free(Q);
}
void ClearQueue(Queue Q)
{
Q -> front = 0;
Q -> rear = 0;
Q -> length = 0;
}
int QueueLength(Queue Q)
{
return Q -> length;
}
ElementType GetHead(Queue Q)
{
if(QueueEmpty(Q)){
printf("Queue is empty!\n");
return 0; //因为函数必须要有返回值,故返回零
}
return Q -> Array[Q -> front];
}
void OutQueue(Queue Q)
{
if(QueueEmpty(Q))
printf("Queue is empty!\n");
else{
Q -> front = MyAdd(Q -> front);
Q -> length --;
}
}
void EnQueue(ElementType E, Queue Q)
{
if(Q -> length == Q -> maxsize)
printf("Queue is full!\n");
else{
Q -> Array[Q -> rear] = E;
Q -> rear = MyAdd(Q -> rear);
Q -> length ++;
}
}
测试文件:
#include "myqueue.h"
int main()
{
Queue testQ = NULL;
testQ = InitQueue();
if(testQ != NULL)
printf("InitQueue succeed!\n");
EnQueue(5, testQ);
EnQueue(12, testQ);
EnQueue(3, testQ);
printf("Now the head is: %d\n", GetHead(testQ));
OutQueue(testQ);
printf("After delete a number, the head is: %d\n", GetHead(testQ));
printf("The length of queue is: %d\n",QueueLength(testQ));
ClearQueue(testQ);
printf("After clear the queue,the length of queue is: %d\n",QueueLength(testQ));
DestoryQueue(testQ);
return 0;
}