使用链表实现队列,提供增删改查接口,最后一步需要清空队列,释放动态申请的内存,第一篇博文,欢迎指正,谢谢。
queue.h
#ifndef QUEUE_H
#define QUEUE_H
#include<stdbool.h>
//队列节点的数据结构,可以根据不同需求进行改造
typedef struct NodeInfo{
int num;
char name[3];
}Item;
//队列节点内容,包括数据结构与指向下一个节点的指针
typedef struct Node
{
Item item;
struct Node* pNext;
}Node;
static Node* p_Head, *p_Tail;//指向队列的头指针,尾指针
static int Length; //队列长度
static int countNode = 0; //队列长度计数器
//初始化,生成一个空队列
void Init();
//在队列尾部添加节点
bool addNode();
//在队列头部删除节点
bool deleteNode();
//判断队列是否为空
bool isEmpty();
//判断队列是否为满
bool isFull();
//遍历队列
void listQueue();
//修改任意位置节点值,传入该节点的顺序位置编号
Node changeNode(int positionNum,Item item);
//队列数据结构生成函数
Item buildItem(int num, char* name);
#endif
queue.c
#include<stdio.h>
#include<malloc.h>
#include<string.h>
#include"queue.h"
void Init() {
int temLength;
p_Head = NULL;
p_Tail = p_Head;
puts("输入队列的长度:");
scanf("%d", &temLength);
Length = temLength;
}
bool isFull() {
return countNode == Length;
}
bool isEmpty() {
return countNode == 0;
}
bool addNode(Item item) {
Node* temNode=NULL;
if (isFull()) {
puts("The queue is Full");
return false;
}
temNode = (Node*)malloc(sizeof(Node));
if ( temNode == NULL) {
puts("Error,applying to the memery!");
return false;
}
if (p_Tail == NULL) { //队列为空的情况
temNode->pNext = NULL;
temNode->item= item;
p_Tail = temNode;
p_Head = p_Tail;
}
else {
temNode->item = item;
temNode->pNext = NULL; //队列不为空
p_Tail->pNext = temNode;
p_Tail = temNode;
}
countNode++;
return true;
}
bool deleteNode() {
if (isEmpty()) {
puts("The queue is Empty!");
return false;
}
Node* temNode;
temNode = p_Head;
p_Head = p_Head->pNext;
temNode->pNext = NULL;
free(temNode);
countNode--;
return true;
}
//不是一个通用方法
void listQueue() {
if (isEmpty()) {
puts("The queue is Empty!");
exit(1);
}
int i = 0;
Node* temNode;
temNode = p_Head;
for (i = 0; i < countNode; i++) {
printf("%d %s\n", temNode->item.num, temNode->item.name);
temNode = temNode->pNext;
}
}
//按从头到尾的顺序修改节点值,并返回修改后的节点值,头结点为第0个
Node changeNode(int positionNum,Item item) {
if (positionNum > countNode) {
puts("要顺序修改的节点不在此队列中");
return *p_Tail;
}
int i = 0;
Node* temNode;
temNode = p_Head;
for (i = 0; i < countNode; i++) {
if (i == positionNum) {
temNode->item = item;
return *temNode;
}
temNode = temNode->pNext;
}
}
//清空队列
void clearQueue() {
while (p_Head != NULL) {
deleteNode();
}
}
//节点构造器
Item buildItem(int num, char* name) {
Item item;
item.num = num;
strcpy(item.name,name);
return item;
}