实验要求:
(1)建立链队列并实现判空、入队、出队、取队头元素等基本操作;
(2)在主函数中测试链队列的基本操作,要求输入一个序列入队,然后再输出队列的内容。
实现提示:
首先定义链队列的数据类型,然后定义链队列的创建、判空、入队、出队、取队头元素等基本操作,最后在主函数中输入一个序列入队,然后再输出队列的内容。
————————我是分割线——————————————————
源代码:
#include<stdio.h>
#include<malloc.h>
//链队列的定义:
typedef int DataType;
struct Node
{
DataType data; //数据域
struct Node *next;
};
typedef struct Node *PNode;
struct Queue
{
PNode f;
PNode r;
};
typedef struct Queue *LinkQueue;
//创建空队列
LinkQueue SetNullQueue_Link()
{
LinkQueue lqueue;
lqueue = (LinkQueue)malloc(sizeof(struct Queue));
if (lqueue != NULL)
{
lqueue->f = NULL;
lqueue->r = NULL;
}
else
printf_s("Alloc failure!\n");
return lqueue;
}
//判断队列是否为空
int IsNullQueue_Link(LinkQueue lqueue)
{
return(lqueue->f == NULL);
}
//入队
void EnQueue_link(LinkQueue lqueue, DataType x)//入队操作
{
PNode p;
p = (PNode)malloc(sizeof(struct Node));//申请结点空间
if (p == NULL)
printf_s("Alloc failure!");
else
{
p->data = x;//数据域赋值
p->next = NULL;//指针域赋值
if (lqueue->f == NULL)//空队列的特殊处理
{
lqueue->f = p;
lqueue->r = p;
}
else
{
lqueue->r->next = p;//插入队尾
lqueue->r = p;//修改队尾指针
}
}
}
//出队
void DeQueue_link(LinkQueue lqueue)
{
struct Node *p;
if (lqueue->f == NULL)//判断队列是否为空
printf_s("It is empty queue!\n");
else
{
p = lqueue->f;//p指向队头结点,以方便后面的释放
lqueue->f = lqueue->f->next;//修改队头指针
free(p);//释放结点空间
}
}
//取队头元素
DataType FrontQueue_link(LinkQueue lqueue)
{
if (lqueue->f == NULL)//判断队列是否为空
{
printf_s("It is empty queue!\n");
return 0;
}
else
{
return(lqueue->f->data);//返回队头结点数据域
}
}
//主函数:
//要求输入一个序列入队,然后再输出队列的内容
void main()
{
LinkQueue lqueue = SetNullQueue_Link(); //创建空队列
int data;
printf_s("请输入进队的元素,以0结束:");
scanf_s("%d,", &data);
while (data)
{
EnQueue_link(lqueue, data); //进队
scanf_s("%d,", &data);
}
printf("出队元素的顺序是:");
while (!IsNullQueue_Link(lqueue))
{
printf_s("%d ", FrontQueue_link(lqueue)); //输出队头元素
DeQueue_link(lqueue); //出队
}
printf_s("\n");
system("pause");
}
运行截图
——————我是分割线——————————————————————
信息安全小萌新注:
1-3已发送,请注意查收!
明天由于信息安全小萌新我要参加数据结构的期中考试,所以新的关于数据结构的博客会发送的晚一点,还是那句话想看小萌新我继续更新博客的还请关注一下!谢谢大家!!!拜谢!!!