队列的链式存储结构。队列常用链表来实现,简称为链队列。
本次设计的链队列有头结点,并且队首指向头结点,队尾指向链尾结点。
队列是先进先出的线性表,在队尾那一端插入元素,在队首那一端删除元素。
c语言代码:
#define _CRT_SECURE_NO_WARNINGS
#include<stdlib.h>
#include<stdio.h>
typedef char ElemType;
typedef struct Qnode
{
ElemType data;
struct Qnode *next;
}Qnode, *Qptr; //定义节点
typedef struct LINKQUEUE
{
Qptr front;
Qptr rear;
}LinkQueue; //定义队首、队尾指针
void InitQueue(LinkQueue *q) //初始化
{
//定义头结点,队首队尾都指向头结点
Qptr firstnode = (Qptr)malloc(sizeof(Qnode));
q->front = q->rear = firstnode;
if (!q->front)
{
exit(0);
}
q->front->next = NULL;
}
void PushQueue(LinkQueue *q, ElemType e) //插入
{
//在队尾插入元素
Qptr p = (Qptr)malloc(sizeof(Qnode));
if (!p)
{
exit(0);
}
p->data = e;
p->next = NULL;
q->rear->next = p;
q->rear = p;
}
void DetQueue(LinkQueue *q, ElemType &e) //出队列
{
//出队列在队首进行
if (q->front == q->rear)
{
printf("队列中无元素!\n");
exit(0);
}
Qptr p = q->front->next;
e = p->data;
q->front->next = p->next;
if (q->rear == p)
{
q->rear = q->front;
}
free(p);
}
void ClearQueue(LinkQueue *q) //清空队列
{
while (q->front)
{
q->rear = q->front->next;
free(q->front);
q->front = q->rear;
}
}
void DisplayQueue(LinkQueue *q) //显示队列
{
if (q->front == q->rear)
{
printf("队列为空!\n");
}
else
{
Qptr p = q->front->next;
while (p)
{
printf("%c ", p->data);
p = p->next;
}
printf("\n");
}
}
int main()
{
ElemType c;
int i;
LinkQueue *q = (LinkQueue*)malloc(sizeof(LinkQueue));
InitQueue(q);
printf("请输入队列元素,元素之间用空格隔开,以“#”结束 \n");
scanf("%c", &c);
while (c != '#')
{
if (c != ' ')
{
PushQueue(q, c);
}
scanf("%c", &c);
}
c = getchar();//清除缓冲区
printf("队列元素为:\n");
DisplayQueue(q);
printf("插入队列元素为: \n");
scanf("%c", &c);
PushQueue(q, c);
printf("队列元素为:\n");
DisplayQueue(q);
printf("出队列次数: \n");
scanf("%d", &i);
for (int j = 0; j < i; j++)
{
DetQueue(q, c);
}
printf("队列元素为:\n");
DisplayQueue(q);
printf("销毁队列 \n");
ClearQueue(q);
DisplayQueue(q);
system("pause");
return 0;
}
运行结果: