一、定义:队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。
二、模型: 队头(front)就是链表头,队尾(rear)就是链表尾。
三、应用:队列在计算机领域的应用也相当广泛,列如计算机的模拟、CPU的作业调度、外围设备联机并发处理系统的应用与图遍历的广度优先搜索法(BFS)。(以上应用目前还不太懂)
四、主要操作:
1、创建空队列:create
2、入队:add
3、出队:del
4、判空:isempty
5、判满:isfull(顺序存储模式——数组)
6、取队头值:getfront
五、队列的实现:
1、顺序存储——数组。利用数组下标对数组长度取余操作可实现循环队列。
模型如下:
//D:\Documents\study\again\数据结构\线性表
/*用数组实现队列,将队列的front指向空,利用判定队列是否已满,是否为空;
当front和rear相等,队列为空;
当rear位于front前一个位置,队列为满;
利用front和rear对MAX取余,可以实现循环队列
*/
#include <stdio.h>
#include <stdlib.h>
#define MAX 8 //定义数组最大长度的宏
#define EORRO -999999999//定义返回值错误的宏
typedef struct que Que; //声明队列名称
typedef int Elementtype;//声明数据类型新名称
struct que{ //定义队列结构体
Elementtype a[MAX];
int front;
int rear;
};
Que *creat(Que *pQ){ //创建一个空队列
pQ=(Que*)malloc(sizeof(Que));
pQ->front=pQ->rear=0;
return pQ;
}
int isfull(Que *pQ){ //判定队列是否已满
return (pQ->rear+1)%MAX==pQ->front;
}
int isempty(Que *pQ){ //判定队列是否为空
return pQ->front==pQ->rear;
}
void add(Que *pQ,Elementtype value){//入队操作
if(!(isfull(pQ))){
pQ->a[(++pQ->rear)%MAX]=value;
}else{
printf("队列已满\n");
}
}
Elementtype del(Que *pQ){//出队操作
Elementtype value=EORRO;
if(!isempty(pQ)){
value=pQ->a[(++pQ->front)%MAX];
}else{
printf("队列已空\n");
}
return value;
}
int main(int argc,char const *argv[]){
Que *pQ=NULL;
pQ=creat(pQ);
for(int i=0;i<MAX;i++){
add(pQ,i);
}
printf("pQ->front=%d\npQ->rear=%d\n",pQ->front,pQ->rear);
for(int i=0;i<MAX;i++){
printf("%d\n",del(pQ));
}
printf("pQ->front=%d\npQ->rear=%d\n",pQ->front,pQ->rear);
return 0;
}
2、链式存储——链表实现。
//D:\Documents\study\again\数据结构\线性表
#include <stdio.h>
#include <stdlib.h>
#define ERROR -999999999
typedef struct que Que;
typedef struct node Node;
typedef int Elementtype;
struct que{
Node *front;
Node *rear;
};
struct node{
Elementtype value;
Node *next;
};
Que *creat(Que *pQ){
pQ=(Que*)malloc(sizeof(Que));
pQ->front=pQ->rear=NULL;
}
int isempty(Que *pQ){
return pQ->front==NULL;
}
void add(Que *pQ,Elementtype value){
Node *pNode=(Node*)malloc(sizeof(Node));
pNode->value=value;
pNode->next=NULL;
if(!isempty(pQ)){
pQ->rear->next=pNode;
pQ->rear=pNode;
}else{
pQ->front=pQ->rear=pNode;
}
}
Elementtype del(Que *pQ){
Elementtype res=ERROR;
Node *ptemp=NULL;
if(isempty(pQ)){
printf("队列为空\n");
}else{
res=pQ->front->value;
ptemp=pQ->front;
if(pQ->front==pQ->rear){
pQ->rear=NULL;
}
pQ->front=pQ->front->next;
free(ptemp);
}
return res;
}
void cle(Que *pQ){
if(!isempty(pQ)){
Node *p=pQ->front;
while(p){
Node *temp=p;
p=p->next;
free(p);
}
}else{
free(pQ);
pQ=NULL;
}
}
int main(int argc,char const *argv[]){
Que *pQ=NULL;
pQ=creat(pQ);
for(int i=0;i<5;i++){
add(pQ,i);
}
while(!isempty(pQ))
printf("%d",del(pQ));
cle(pQ);
return 0;
}