/************************************
* 链队列的基本操作(C语言源代码)
* 2021/8/19
*************************************/
#include<stdio.h>
#include<stdlib.h>
typedef struct QNode
{
int data;
struct QNode * next;
}QNode,*QueuePtr;
typedef struct
{
QueuePtr front;
QueuePtr rear; /*每个指针都是指向上述QNode结点类型的指针*/
}LinkQueue;
/*①链队列的初始化*/
int Init_LinkQueue(LinkQueue*q)
{
q->rear = q->front = (LinkQueue*)malloc(sizeof(LinkQueue));
if (!q->front)
return -1;
else
{
q->front->next = NULL;
return 1;
}
}
/*②链队列的入队*/
int Enter_LinkQueue(LinkQueue* q,int e)
{
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
if (!p)
return -1;
else
{
p->data = e;
p->next = NULL;
q->rear->next = p;
q->rear = p;
return 1;
}
}
/*③取队头元素*/
int Get_Head(LinkQueue* q)
{
if (q->front == q->rear)
return -1;
else
{
return q->front->next->data;
}
}
/*④链队列的出队*/
int Out_LinkQueue(LinkQueue* q, int* e)
{
if (q->front == q->rear)
return -1;
else
{
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
p=q->front->next;
*e = p->data;
q->front->next = p->next;
if (p == q->rear)q->rear = q->front;
free(p);
return *e;
}
}
/*⑤销毁链队列*/
int Destroy_LinkQueue(LinkQueue* q)
{
while (q->front)
{
QueuePtr p = (QueuePtr)malloc(sizeof(QNode));
p = q->front->next;
free(q->front);
q->front = p;
return 1;
}
}
void main()
{
/*①链队列的初始化*/
LinkQueue* q1 = (LinkQueue*)malloc(sizeof(LinkQueue));
int a = 0;
a = Init_LinkQueue(q1);
//printf("%d",a);
/*②链队列的入队*/
int i,b = 0;
for (i = 100; i < 105; i++)
{
b = Enter_LinkQueue(q1, i + 1);
}
//printf("%d",b);
/*③取队头元素*/
int d = 0;
d = Get_Head(q1);
//printf("%d",d);
/*④链队列的出队*/
int j,c=0;
int* e1 = &c;
for (j = 0; j < 5; j++)
{
c = Out_LinkQueue(q1, e1);
printf("%d\n", c);
}
/*⑤销毁链队列*/
int f = 0;
f = Destroy_LinkQueue(q1);
printf("%d",f);
}
链队列的基本操作(C语言源代码)
最新推荐文章于 2023-02-24 22:26:04 发布
本文详细介绍了如何使用C语言实现链队列的基本操作,包括队列的初始化、入队、出队、查看队首元素以及判断队列是否为空等关键函数的编写和实现过程。
摘要由CSDN通过智能技术生成