C语言队列实现
队列介绍
队列是一种数据结构,它遵循先进先出(FIFO,First-In-First-Out)的原则。这意味着队列中的第一个元素是最早被添加的,也是最早被移除的。队列在计算机科学中广泛应用于任务调度、缓冲处理、打印队列等场景。
队列实现
#include<stdio.h>
#include<malloc.h>
struct node{
int data;
struct node *pnext;
};
struct queue{
struct node *front;
struct node *rear;
};
struct queue *phead = NULL;//定义全局变量,方便调用
void createSpaceForQueue();
void initQueue(struct queue *phead);
void enQueue(struct queue *phead, int e);
void deQueue(struct queue *phead, int e);
void showQueue(struct queue *phead);
void clearQueue(struct queue *phead);
int main(){
createSpaceForQueue();
initQueue(phead);
for(int i = 0; i < 5; i++){
enQueue(phead, i);
}
showQueue(phead);
deQueue(phead, 0);
deQueue(phead, 0);
deQueue(phead, 0);
showQueue(phead);
clearQueue(phead);
return 0;
}
void createSpaceForQueue(){//为队列分配内存空间
phead = (struct queue*)malloc(sizeof(struct queue));//队列的头部是一个空结点;
phead ->front=NULL;
phead->rear = NULL;
}
void initQueue(struct queue *phead){//得到一个空队列
phead->front = phead->rear = (struct node*)malloc(sizeof(struct node));
if (!phead->front){
printf("空间分配错误,队列初始化失败!\n");
return;
}
else{
phead->front->pnext = NULL;
printf("队列初始化成功!\n");
}
}
void enQueue(struct queue *phead,int e){//向队列中插入元素
struct node *pnew = NULL;
pnew = (struct node*)malloc(sizeof(struct node));
if (!pnew){
printf("空间分配错误,元素%d插入失败!", e);
}
else{
pnew->data = e;
pnew->pnext = NULL;
phead->rear->pnext = pnew;//将新的结点连接在头节点的后面;
phead->rear = phead->rear->pnext;//头节点指针后移,保证每次都指向最后一个结点;
printf("元素%d插入成功!\n", e);
}
}
void deQueue(struct queue *phead, int e){//删除元素
struct node *p = (struct node*)malloc(sizeof(struct node));
if (phead->front == phead->rear){
printf("此队列为空,删除失败!\n");
}
else{
p = phead->front->pnext;
e = p->data;
phead->front->pnext = p->pnext;
if (phead->rear == p){
phead->rear = phead->front;
}
free(p);
printf("元素%d已从队列上删除!\n", e);
}
}
void showQueue(struct queue *phead){//打印队列中的元素
struct node *pfind = NULL;
pfind = phead->front->pnext;
while (pfind != NULL){
printf("%d ", pfind->data);
pfind = pfind->pnext;
}
printf("\n");
}
void clearQueue(struct queue *phead){//清除结点,释放内存;
struct node *pcl = phead->front->pnext;
phead->front->pnext = NULL;
phead->front = NULL;
phead->rear = NULL;
struct node *p = NULL;
while (pcl!=NULL){
p = pcl;
pcl = pcl->pnext;
free(p);
}
printf("\n队列被清除,内存已释放!\n");
}