队列(C语言)
本文参考自《大话数据结构》
定义
队列(queue)是只允许在一端进行插入操作,而在另一端进行删除操作的线性表,简称FIFO(First In First Out),允许插入的一端称为队尾,允许删除的一端称为队头。
抽象数据结构
ADT 队列(Queue)
Data
struct Queue{
SElemType data; //数据域
struct Queue* front; //前驱
struct Queue* next; //后继
};
struct LinkQueue{
struct Queue* top; //队头指针
struct Queue* rear; //队尾指针
int count = 0; //队列中元素个数
};
Operation
InitQueue(*Q):初始化操作,建立一个空队列Q
DestoryQueue(*Q):若队列Q存在,则销毁它
ClearQueue(*Q):将队列Q清空
QueueEmpty(Q):若队列Q为空,返回true,否则返回false
GetHead(Q,*e):若队列Q存在且非空,用e返回队列Q的队头元素
EnQueue(*Q, e):若队列Q存在,插入新元素e到队列Q中并成为队尾元素
DeQueue(*Q, *e):删除队列Q中队头元素,并用e返回其值
QueueLength(Q):返回队列Q的元素个数
endADT
具体实现
#include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#define ERROR 0
#define OK 1
typedef int Status;
typedef int SElemType;
struct Queue{
SElemType data; //数据域
struct Queue* front; //前驱
struct Queue* next; //后继
};
struct LinkQueue{
struct Queue* top;
struct Queue* rear;
int count = 0;
};
/* 建立一个空的队列 */
LinkQueue* InitQueue(){
LinkQueue* q = (LinkQueue*)malloc(sizeof(LinkQueue));
q->top = NULL;
q->rear = NULL;
q->count = 0;
return q;
}
/* 销毁队列 */
void Dest