头文件
#pragma once//利用带头节点的单链表实现队列,队头为第一个数据节点typedef struct Node
{int data;struct Node *next;
}Node;//数据节点typedef struct HNode
{struct Node *front;//队头指针struct Node *rear;//队尾指针
}HNode,*PLQueue;//头节点void InitQueue(PLQueue pl);//入队
bool Push(PLQueue pl,int val);//获取队头的值,但不删除
bool GetTop(PLQueue pl,int *rtval);//获取队头的值,且删除
bool Pop(PLQueue pl,int *rtval);bool IsEmpty(PLQueue pl);void Destroy(PLQueue pl);
cpp文件
#include <stdio.h>
#include <assert.h>
#include <stdlib.h>
#include "lqueue.h"
//利用带头节点的单链表实现队列,队头为第一个数据节点void InitQueue(PLQueue pl)
{assert(pl != NULL);pl->front = NULL;pl->rear = NULL;
}//入队
bool Push(PLQueue pl,int val)
{Node *p = (Node *)malloc(sizeof(Node));p->data = val;p->next = NULL;if(IsEmpty(pl)){pl->front = p;pl->rear = p;}else{pl->rear->next = p;pl->rear = p;}return true;
}//获取队头的值,但不删除
bool GetTop(PLQueue pl,int *rtval)
{if(IsEmpty(pl)){return false;}if(rtval != NULL){*rtval = pl->front->data;}return true;
}//获取队头的值,且删除
bool Pop(PLQueue pl,int *rtval)
{if(IsEmpty(pl)){return false;}if(rtval != NULL){*rtval = pl->front->data;}Node *p = pl->front;pl->front = p->next;free(p);if(pl->front == NULL) //已经删除最后一个节点{pl->rear = NULL;}return true;
}bool IsEmpty(PLQueue pl)
{return pl->front == NULL;
}void Destroy(PLQueue pl)
{Node *q;for(Node *p = pl->front;p->next != NULL;p = p-> next){q = p;free(q);}pl -> front = NULL;pl -> rear = NULL;
}
主函数
#include <stdio.h>
#include "lqueue.h"int main()
{HNode head;InitQueue(&head);for(int i=0;i<15;i++){Push(&head,i);}int tmp;while(!IsEmpty(&head)){Pop(&head,&tmp);printf("%d\n",tmp);}return 0;
}