一.实验内容
(1)设计一个字符型的链队列;
(2)编写队列的进队、出队、读队头元素、显示队列中全部元素程序;
(3)设计一个选择式菜单,以菜单方式选择队列的各种基本操作。
二.实验要求
(1)掌握队列的特点及其描述方法;
(2)用链式结构实现一个队列;
(3)掌握队列的各种基本操作;
(4)掌握队列的简单应用程序。
#include<stdio.h>
#include<stdlib.h>
#include<malloc.h>
typedef struct Node{
int data;
struct Node *next;
}Node;
typedef struct Queue{
Node *Front,*Rear;
}Queue;
void Initqueue(Queue &Q){
Q.Front = Q.Rear =(Node*)malloc(sizeof(Node));
Q.Front->next = NULL;
}
void EnQueue(Queue &Q,int e){
Node *s=(Node*)malloc(sizeof(Node));
s->data = e;
s->next = NULL;
Q.Rear->next = s;
Q.Rear = s;
}
int IsEmpty(Queue &Q){
if(Q.Front == Q.Rear)
return 1;
else
return 0;
}
int DeQueue(Queue &Q,int &x)
{
if(Q.Front==Q.Rear)
return 0;
Node *p = Q.Front->next;
x = p->data;
Q.Front->next=p->next;
if(Q.Rear == p)
Q.Rear = Q.Front;
free(p);
return 1;
}
void show(Queue Q)
{
Node *p = Q.Front->next;
while(p!=NULL)
{
printf("%d",p->data);
p = p->next;
}
}
void main(){
Queue Q;
int j=1,e,n,i,o;
int choose;
while(j)
{
printf("\n\t\t------------队列系统----------");
printf("\n\t\t*\t 1----创建队列\t\t\t*");
printf("\n\t\t*\t 2----入队列\t\t\t*");
printf("\n\t\t*\t 3----出队列\t\t\t*");
printf("\n\t\t*\t 4----遍历队列\t\t\t*");
printf("\n\t\t*\t 0----退出\t\t\t*");
printf("\n\t\t请选择菜单号码\t\t\t*");
scanf("%d",&choose);
printf("\n");
if(choose == 1)
{
Initqueue(Q);
printf("创建成功\n");
}
else if(choose == 2)
{
printf("输入插入的数量:");
scanf("%d",&n);
for(int i = 0; i < n; i++)
{
printf("输入第%d个的值:",i+1);
scanf("%d",&e);
EnQueue(Q,e);
}
}
else if(choose == 3)
{
o = DeQueue(Q,n);
if(o == 1){
printf("出队列成功");
printf("出队列的元素值为%d",n);
}
}
else if(choose == 4)
{
show(Q);
}
else if(choose == 0)
{
j = 0;
}
else
printf("输入错误!\n");
}
}
运行结果: