队列是一种特殊的表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的表。进行插入操作的端称为队尾,进行删除操作的端称为队头
队列的实现同栈一样,都可以通过链表和线性表实现。下面是链表实现的队列
头文件queue.h
struct Node;
typedef int Element;
typedef struct Node *ptrToNode;
struct Queue;
typedef struct Queue *ptrToQueue;
//创建队列
ptrToQueue createQueue();
//入队
void enQueue(ptrToQueue Q,Element e);
//出队
Element deQueue(ptrToQueue Q);
//对是否为空
int isEmpty(ptrToQueue Q);
//销毁队列
void destoryQueue(ptrToQueue &Q);
//获得队列大小
int getSize(ptrToQueue Q);
实现
#include <stdio.h>
#include <stdlib.h>
#include "queue.h"
struct Node{
Element datd;
ptrToNode next;
};
struct Queue{
ptrToNode front,rear;
int size; //队列大小
};
//创建队列
ptrToQueue createQueue(){
ptrToQueue ptr = (ptrToQueue)malloc(sizeof(struct Queue));
if(ptr==NULL){
printf("malloc failed\n");
return NULL;
}
ptr->front = NULL;
ptr->rear = NULL;
ptr->size = 0;
return ptr;
}
//入队
void enQueue(ptrToQueue Q,Element e){
if(Q == NULL){
printf("please create queue\n");
return;
}
ptrToNode ptr = (ptrToNode)malloc(sizeof(struct Node));
if(ptr==NULL){
printf("malloc failed\n");
return;
}
ptr->datd = e;
ptr->next = NULL;
if(Q->size == 0){
Q->rear = ptr;
Q->front = ptr;
Q->size++;
}else{
Q->rear->next = ptr;
Q->rear = ptr;
Q->size++;
}
}
//出队
Element deQueue(ptrToQueue Q){
if(Q == NULL){
printf("please create queue\n");
return NULL;
}
if(isEmpty(Q)){
printf("the queue is empty");
return NULL;
}else{
ptrToNode ptr = Q->front;
Q->front = ptr->next;
Element e = ptr->datd;
Q->size--;
free(ptr);
return e;
}
}
//为空
int isEmpty(ptrToQueue Q){
if(Q == NULL){
printf("please create queue\n");
return 0;
}
return Q->size == 0;
}
//销毁
void destoryQueue(ptrToQueue &Q){
if(Q == NULL){
printf("the queue is null\n");
return;
}
while(Q->size>0){
deQueue(Q);
}
free(Q);
Q = NULL;
}
//获得大小
int getSize(ptrToQueue Q){
if(Q == NULL){
printf("the queue is null\n");
return NULL;
}
return Q->size;
}
测试
#include <stdio.h>
#include "queue.h"
int main(){
//创建
ptrToQueue Q = createQueue();
enQueue(Q,1);
enQueue(Q,2);
enQueue(Q,3);
enQueue(Q,4);
enQueue(Q,5);
int size = getSize(Q);
for(int i=0;i<size;i++)
printf("%d ",deQueue(Q));
//销毁
destoryQueue(Q);
return 0;
}