队列是一种特殊的线性表,特殊之处在于它只允许在表的前端(front)进行删除操作,而在表的后端(rear)进行插入操作,和栈一样,队列是一种操作受限制的线性表。进行插入操作的端称为队尾,进行删除操作的端称为队头。队列中没有元素时,称为空队列。
队列的数据元素又称为队列元素。在队列中插入一个队列元素称为入队,从队列中删除一个队列元素称为出队。因为队列只允许在一端插入,在另一端删除,所以只有最早进入队列的元素才能最先从队列中删除,故队列又称为先进先出(FIFO—first in first out)线性表。
#include "stdio.h"
#include "stdlib.h"
#define MAX_SIZE (20)
//定义一个结点结构体
struct Node{
int data;
struct Node* next;
};
//定义一个队列结构体
struct Queue{
struct Node* head;
struct Node* tail;
int size;
};
//创建一个结点
struct Node* creatNode(int data){
struct Node* newNode = (struct Node*)malloc(sizeof(struct Node));
newNode->data = data;
newNode->next = NULL;
return newNode;
}
//创建一个队列
struct Queue* creatQueue(void){
struct Queue* newQueue = (struct Queue*)malloc(sizeof(struct Queue));
//闂備礁鎲$敮妤冩崲閸岀儑缍栭柟鐗堟緲缁€宀勬煛瀹ュ啫濡介柟顖涚懃闇夐柨婵嗙箲鐎氾拷
newQueue->head = NULL;
newQueue->tail = NULL;
newQueue->size = 0;
return newQueue;
}
//入队:链表的尾插法
void push(struct Queue* myQueue,int data){
if(myQueue->size>=MAX_SIZE){
printf("入队失败,队列满了!\n");
return;
}
//创建一个新节点
struct Node *newNode = creatNode(data);
if(myQueue->size == 0){//当队列为空的时候
//尾指针和头指针指向本节点
myQueue->tail = myQueue->head = newNode;
}
else{
//队尾结点指向新节点
myQueue->tail->next = newNode;
//队尾指针指向新节点
myQueue->tail = newNode;
}
myQueue->size++;
}
//出队:从队首出队
void pop(struct Queue* myQueue){
if(myQueue->size == 0){
printf("出队失败,队列为空!\n");
return;
}
else{
//定义一个指针,指向头结点的下一个结点
struct Node* nextNode = myQueue->head->next;
//释放头结点的空间
free(myQueue->head);
//将头指针指向新的队首结点
myQueue->head = nextNode;
myQueue->size--;
}
}
//获取队首元素
int front(struct Queue* myQueue){
if(myQueue->size == 0){
printf("获取队首元素失败,队列为空!\n");
return 0;
}
return myQueue->head->data;
}
//判定队列是否为空
int empty(struct Queue* myQueue){
if(myQueue->size == 0){
return 0;
}
return 1;
}
int main(){
int i;
//创建一个队列
struct Queue* myQueue = creatQueue();
//连续入队
for(i=0;i<25;i++){
push(myQueue,i);
}
while(empty(myQueue)){
//获取队首元素
printf("%d ",front(myQueue));
//出队
pop(myQueue);
}printf("\n");
return 0;
}
By Urien 2021年2月1日 12:09:38