/**
* 实现链队各种基本运算的算法
* 目的:
* 领会链队存储结构和掌握链队中各种基本运算算法设计
* 主要功能:
* 1、初始化链队q
* 2、判断链队q是否非空
* 3、依次进链队元素a、b、c
* 4、出队一个元素,输出该元素
* 5、依次进链队元素d、e、f
* 6、输出出队序列
* 7、释放链队
*/
#include <stdio.h>
#include <malloc.h>
#include <stdbool.h>
typedef char ElemType;
typedef struct DataNode
{
ElemType data; // 数据域
struct DataNode *next; // 指针域
}DataNode; // 声明链队数据结点类型
typedef struct
{
DataNode *queue_front; // 队头指针
DataNode *queue_rear; // 队尾指针
}LinkQuNode; // 声明链队类型
/*----------------------初始化队列q------------------------*/
static void init_queue(LinkQuNode *&q)
{
q = (LinkQuNode *)malloc(sizeof(LinkQuNode)); // 动态分配存储空间
q->queue_front = q->queue_rear = NULL;
}
/*----------------------销毁队列q------------------------*/
static void destroy_queue(LinkQuNode *&q)
{
DataNode *p = q->queue_front; // p指向队头数据结点
DataNode *r;
if(p != NULL)
{
r = p->next; // r指向队列中第一个数据结点
while(r != NULL)
{
free(p);
// p,r同步后移一个结点
p = r;
r = p->next;
}
}
free(p);
free(q); // 释放链队结点占用空间
}
/*----------------------判断队列q是否空------------------------*/
static bool queue_empty(LinkQuNode *q)
{
return (q->queue_rear == NULL);
}
/*----------------------入队------------------------*/printf(" (3)链队为%s\n", (queue_empty(q) ? "空" : "非空"));
static void enter_queue(LinkQuNode *&q, ElemType e)
{
DataNode *p;
// 创建新结点p
p = (DataNode *)malloc(sizeof(DataNode)); // 动态分配存储空间
p->data = e;
p->next = NULL;
// 若链队为空,则新结点既是队首结点又是队尾结点
if(q->queue_rear == NULL)
q->queue_front = q->queue_rear = p;
else
{
// 将新结点p链到队尾,并将queue_rear指向它
q->queue_rear->next = p;
q->queue_rear = p;
}
}
/*----------------------出队------------------------*/
static bool de_queue(LinkQuNode *&q, ElemType &e) // 指针的引用
{
DataNode *t;
if(q->queue_rear == NULL) // 队列为空
return false;
t = q->queue_front; // t指向第一个数据结点
if(q->queue_front == q->queue_rear) // 队列中只有一个结点时
{
q->queue_front = q->queue_rear = NULL;
}
else // 队列中有多个结点时
{
q->queue_front = q->queue_front->next; // 队首指针后移一个结点
}
e = t->data; // 从t结点中提取数据元素
free(t); // 释放t结点
return true;
}
int main(int argc, char *argv[])
{
ElemType e;
LinkQuNode *q;
printf("链队的基本运算如下:\n");
printf(" (1)初始化链队q\n");
init_queue(q);
printf(" (2)依次进链队元素a、b、c\n");
enter_queue(q, 'a');
enter_queue(q, 'b');
enter_queue(q, 'c');
printf(" (3)链队为%s\n", (queue_empty(q) ? "空" : "非空"));
if(!de_queue(q, e))
printf("\t提示:队空,不能出队\n");
else
printf(" (4)出队一个元素%c\n", e);
printf(" (5)依次进链队元素d、e、f\n");
enter_queue(q, 'd');
enter_queue(q, 'e');
enter_queue(q, 'f');
printf(" (6)出链队序列: ");
while(!queue_empty(q))
{
de_queue(q, e);
printf("%c ", e);
}
printf("\n");
printf(" (7)释放链队\n");
destroy_queue(q);
return 0;
}
运算结果:
链队的基本运算如下:
(1)初始化链队q
(2)依次进链队元素a、b、c
(3)链队为非空
(4)出队一个元素a
(5)依次进链队元素d、e、f
(6)出链队序列: b c d e f
(7)释放链队