c语言代码实现
注:函数功能和注释都在代码里
#include<stdio.h>
#include<stdlib.h>
//学生类型定义
typedef struct
{
int age;
int height;
double weigth;
}Student;
//队列节点类型
typedef struct _node
{
Student stu;
struct _node* next;
}Node;
//队列头指针和尾指针类型
typedef struct
{
Node* front;
Node* rear;
}LinkQueue;
//初始化队列函数
int initQueue(LinkQueue *q)
{
//为队列生成一个头节点,然后队列的头指针指向头节点
q->front = (Node*)malloc(sizeof(Node));
q->rear = q->front;//初始化时,头尾指向同一个节点
if (!q->front)exit(-1);
//设置头节点的next值为空
q->front->next = NULL;
return 1;
}
//销毁队列函数
int destoryQueue(LinkQueue* q)
{
if (!q->front)return 0;
while (q->front != NULL)
{
//从队列头部开始释放节点
q->rear = q->front->next;
free(q->front);
q->front = q->rear;
}
return 1;
}
//入队列函数
int insertQueue(LinkQueue *q,Node *node )
{
if (!q->front)return 0;
q->rear->next = node;
q->rear = node;
q->rear->next = NULL;
return 1;
}
//节点值复制函数
void copyValue(Node *node1,Node *node2)
{
if (!node2)return ;
*node1 = *node2;
node1->next = NULL;
}
//出队列函数
int deleteQueue(LinkQueue* q, Node* node)
{
if (q->front == q->rear)return 0;
Node* p = q->front->next;//从头节点的下一个节点开始释放
if (!p)return 0;
copyValue(node,p);
q->front->next = p->next;
//如果队列的尾指针指向的是头指针的下一个,那么这个节点是最后一个数据节点
if (q->rear == p)q->rear == q->front;
free(p);
return 1;
}
//显示学生信息函数
void displayValue(Student* stu)
{
if (!stu)return;
printf("age=%5d,weight=%5d,height=%5lf\r\n",stu->age, stu->height , stu->weigth );
}
//遍历队列函数
int displayQueue(LinkQueue *q)
{
if (q->front == q->rear)return 0;
Node* p = q->front->next;
while (p!=NULL)
{
displayValue(&p->stu);
p = p->next;
}
return 1;
}
//为学生输入信息函数
void inputValue(Student* stu)
{
if (!stu)return;
printf("输入学生年龄,身高,体重\n");
scanf_s("%d%d%lf", &stu->age, &stu->height, &stu->weigth);
}
//生成节点函数
Node* createNode(Student *stu)
{
Node* node = (Node *)malloc(sizeof(Node));
if (!node)return NULL;
node->stu = *stu;//把学生信息传给节点
node->next = NULL;
return node;
}
//测试程序:生成n个数据节点
void test(LinkQueue *q ,int n)
{
Student stu;
Node* node;
for (int i = 0; i < n; i++)
{
inputValue(&stu);//输入学生信息
node = createNode(&stu);//创建节点
insertQueue(q, node);//插入节点
}
}
int main()
{
LinkQueue q;
//初始化队列
initQueue(&q);
//测试程序:增加3个队列节点
test(&q,3);
printf("打印增加3个节点后的队列信息\n");//打印增加3个节点后的队列信息
displayQueue(&q);
//出队列
Node node;
deleteQueue(&q, &node);
printf("打印出队列后的队列信息\n");//打印出队列后的队列信息
displayQueue(&q);
printf("打印出队列的成员信息\n");//打印出队列的成员信息
displayValue(&node.stu);
//销毁队列
destoryQueue(&q);
return 0;
}
2829

被折叠的 条评论
为什么被折叠?



