链式队列(linked queue)是2018年公布的计算机科学技术名词,采用链式存储结构的队列。
head.h
#ifndef __LS_H__
#define __LS_H__
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
typedef int datedef;
typedef struct Node
{
union // 数据域
{
int len; // 头结点的数据域 (链表长度)
datedef date; // 其他结点的数据域
};
struct Node *next; // 指针域
} *linklist, Linklist;
typedef struct QUE
{
struct Node *head;
struct Node *rear;
} *que;
que creat(); // 创建新队列
linklist creat_L(); // 创建队列结点
void output(que Q); // 遍历
int h_del(que Q); // 头删
int r_insert(que Q, datedef e); // 尾插
void L_free(que Q); // 链表释放
#endif
fun.c
#include "head.h"
que creat() // 创建链表队列
{
que Q = (que)malloc(sizeof(struct QUE));
if (Q == NULL)
{
return NULL;
}
linklist L = (linklist)malloc(sizeof(Linklist));
if (L == NULL)
{
return NULL;
}
L->len = 0;
L->next = NULL;
Q->head = L;
Q->rear = L;
return Q;
}
linklist creat_L() // 创建队列结点
{
linklist L = (linklist)malloc(sizeof(Linklist));
if (L == NULL)
{
return NULL;
}
L->date = 0;
L->len = 0;
}
void output(que Q) // 遍历
{
if (Q->head->next == NULL || Q == NULL)
{
printf("遍历失败\n");
}
printf("输出的元素是:\n");
linklist p = Q->head->next;
while (p)
{
printf("%d\t", p->date);
p = p->next;
}
puts("");
printf("该队列有%d个元素。\n", Q->head->len);
}
/*
*for(int i=0;i<p->len;i++)
*{
*p=p->next;
*printf("%d\t",p->date);
*}
*puts("");
*/
int r_insert(que Q, datedef e) // 入队
{
if (Q == NULL)
{
printf("队列不存在\n");
return -1;
}
linklist p = creat_L();
p->date = e;
Q->rear->next = p;
Q->rear = p;
Q->head->len++;
return 0;
}
int h_del(que Q) // 出队
{
if (Q->head->next == NULL || Q == NULL)
{
printf("出队失败\n");
return -1;
}
linklist p = Q->head->next;
printf("%d\t出队", p->date);
Q->head->next = p->next;
if (Q->rear = p)
{
Q->rear = Q->head;
}
Q->head->len--;
free(p);
p = NULL;
return 0;
}
void L_free(que Q) // 链表释放
{
if (Q == NULL)
{
printf("队列不存在\n");
return;
}
while (Q->head->len)
{
h_del(Q); // 出队
printf("结点空间已释放\n");
}
free(Q->head);
Q->head = NULL;
Q->rear = NULL;
free(Q);
Q = NULL;
printf("队列完全释放\n");
}
main.c
#include "head.h"
int main(int argc, const char *argv)
{
que Q = creat(); // 创建
int n;
datedef s, e;
printf("你要入队的元素个数:");
scanf("%d", &n);
for (int i = 0; i < n; i++)
{
printf("你要入队的元素是:");
scanf("%d", &s);
r_insert(Q, s); // 入队
}
output(Q);
char a[10];
while (1)
{
printf("是否让:%d\t出队?yes/no", Q->head->next->date);
scanf("%s", a);
if (strcmp(a, "yes") == 0)
{
h_del(Q); // 出队
puts("");
}
else
{
break;
}
}
output(Q);
L_free(Q); // 链表释放
}