实验三 队列
一、实验目的
1.深入了解队列的定义和特性。
2.掌握队列的数组表示、链表表示以及相应操作的实现,巩固对这两种结构的构造方法的掌握。
3. 会灵活运用队列结构解决某些实际问题。
二、实验内容
- 顺序队列的基本操作的实现(初始化、赋值、取值、插入、删除等)。
循环队列源程序
#include<stdio.h>
//#include<stdlib.h>
#include <process.h>
#define MAXQSIZE 100//队列可能达到的最大长度
#define OK 1
#define ERROR 0
#define OVERFLOW -1
typedef int QElemType;
typedef int Status;
typedef struct{
QElemType *base;//存储空间的基地址
int front;//头指针
int rear;//尾指针
}SqQueue;
Status InitQueue(SqQueue &Q)
{//构造一个空队列Q
Q.base=new QElemType[MAXQSIZE];//为队列分配一个最大容量为MAXQIZE的数组空间
if(!Q.base) exit(OVERFLOW);//存储分配失败
Q.front=Q.rear=0;//头指针和尾指针置为零,队列为空
return OK;
}
int Assign(SqQueue &Q,QElemType e)//赋值
{ int i,N;
if((Q.rear+1)%MAXQSIZE==Q.front) return ERROR;//队满
printf("请输入入队元素个数");
scanf("%d",&N);
printf("请输入入队元素");
for(i=0;i<N;i++) {
scanf("%d",&e);
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%MAXQSIZE;
printf("%d已入队\n",e);
}
return OK;
}
int QueueLength(SqQueue Q)
{//返回Q的元素个数,即队列的长度
return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
}
Status EnQueue(SqQueue &Q,QElemType e)//入队
{
if((Q.rear+1)%MAXQSIZE==Q.front)
return ERROR;
Q.base[Q.rear]=e;
Q.rear=(Q.rear+1)%MAXQSIZE;
printf("%d已入队\n",e);
return OK;
}
Status DeQueue(SqQueue &Q,QElemType &e)//出队
{
if(Q.rear==Q.front)return ERROR;
e=Q.base[Q.front];
Q.front=(Q.front+1)%MAXQSIZE;
printf("%d已出队\n",e);
return OK;
}
QElemType GetHead(SqQueue Q,QElemType &e)
{
if(Q.rear!=Q.front)
e=Q.base[Q.front];
printf("队头元素为:%d",e);
return e;
}
int main(){
SqQueue Q;
QElemType e;
if(InitQueue(Q)) printf("初始化成功!\n");
Assign(Q,e);
printf("请输入入队元素:");
scanf("%d",&e);
EnQueue(Q,e);
DeQueue(Q,e);
GetHead(Q,e);
}
运行结果