当前位置:文档之家› 第4次实验报告

第4次实验报告

第4次实验报告
实验4 队列
实验日期:20 年月日实验类型:应用
实验概述:
一、实验目的
本次实验的主要目的是使学生熟练掌握队列的基本操作,能够采用链队解决实际问题。

二、实验要求
熟悉队列有关算法,掌握链队的初始化、入队、出队、输出操作。

三、实验步骤
用链队结构实现队列的初始化、入队、出队、输出操作。

步骤如下:
(1)输入队列长度
(2)显示队列元素
(3)输入需要入队的元素
(4)入队,显示队列元素
(5)元素出队,并显示队列的元素
实验结果如图:
四、实验环境(使用的软件和设备)
(1)实习器材:多媒体计算机。

(2)实习地点:校内多媒体机房。

(3)实习软件: VC 6.0
实验内容:
【实验过程】(实验步骤、记录、数据、分析)
实验过程(提示)
#include<stdio.h>
#include<malloc.h>
typedef int elemtype;
typedef struct qnode{
elemtype data;
struct qnode *next;
}Qnode;
typedef struct {
Qnode *front;//队头指针始终指向单链表的头结点
Qnode *rear;//队尾指针始终指向单链表的尾结点
}liqueue;//队列的存储结构为两个指向队头,和队尾的队列结点指针void initqueue(liqueue *&q){//初始状态
q = (liqueue *)malloc(sizeof(liqueue));
q->front = q->rear = NULL;
}
void destroyqueue(liqueue *&q){//销毁队列
Qnode *p = q->front, *r;
if (p != NULL){
r = p->next;
while (r != NULL){
free(p);
p = r;
r = p->next;
}
}
free(p);
free(q);
}
bool queueempty(liqueue *q){//判断队列是否为空
return (q->rear == NULL);
}
void enqueue(liqueue *&q, elemtype e){//入队
Qnode *p;
p = (Qnode *)malloc(sizeof(Qnode));
p->data = e;
p->next = NULL;
if (q->rear == NULL)
q->front = q->rear = p;
else
{
q->rear->next = p;
q->rear = p;
}
}
bool dequeue(liqueue *&q, elemtype &e){//出队
Qnode *t;
if (q->rear == NULL){//判断队列是否为空
return false;
}
t = q->front;
if (q->front == q->rear)
q->front = q->rear = NULL;
else
q->front = q->front->next;
e = t->data;
free(t);
return true;
}
void printqueue(liqueue *q)//输出当前队中的数字,不出队{
Qnode *pnode = q->front;
if (pnode == NULL)
{
printf("队空\n");
return;
}
printf("队列中现在的元素为:\n");
while (pnode != q->rear)
{
printf("%d ", pnode->data);
pnode = pnode->next;
}
printf("%d ", pnode->data);
printf("\n");
}
void GetLength(liqueue *q)//得到队列的长度
{
int nlen = 0;
Qnode *pnode = q->front;
if (pnode != NULL)
{
nlen = 1;
}
while (pnode != q->rear)
{
/*遍历队列*/
pnode = pnode->next;
nlen++;
}
printf("队列长度为 : ");
printf("%d\n", nlen);
}
void main()
{
elemtype e;
liqueue *q;
initqueue(q);
elemtype x;
printf("设定队列长度 ");
elemtype y;
scanf("%d", &y);
int a[100];
printf("输入要入队的数字: ");
int i;
for (i = 0; i<y; i++){
scanf("%d", &a[i]);
}
x = i;
for (int j = 0; j < x; j++){
enqueue(q, a[j]);
}
printqueue(q);
printf("输入再入队的数字");
elemtype z;
scanf("%d", &z);
enqueue(q, z);
printqueue(q);
if (dequeue(q, e) == 0)
printf("空队\n");
else
printf("出队元素: %d\n", e);
printqueue(q);
destroyqueue(q);
}
【结果实验记录】(图形或图像)
1.说明掌握情况
2.裁图说明实验结果
【心得体会、问题和建议】
成绩:
批阅日期:。

相关主题