#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#include<time.h>
#define TURE 1
#define FALSE 0
#define OK 1
#define ERROR 0
#define INFEASIBLE -1
#define OVERFLOW -2
#define MAXSIZE 100 //最大队列长度
typedef int Status;
typedef struct{
int stuNo;
char name[10];
}Student;
typedef struct{
Student* base;//初始化的动态分配存储空间
int front; //头指针,如果队列不空,指向队列的头元素
int rear; //尾指针,如果队列不空,指向队列尾元素的下一个位置
}SqQueue;
Status InitQueue(SqQueue &Q){
Q.base = (Student*)malloc(MAXSIZE*sizeof(Student));
if(!Q.base) return OVERFLOW;//分配失败的情况
Q.front = Q.rear =0;
return OK;
}
int QueueLength(SqQueue Q){
return (Q.rear-Q.front+MAXSIZE)%MAXSIZE;
}
Status EnQueue(SqQueue &Q,Student s){
//插入元素s为Q的新的队尾元素
if((Q.rear+1)%MAXSIZE==Q.front) return ERROR;// 队列满
Q.base[Q.rear]=s;
Q.rear =(Q.rear+1)%MAXSIZE;
return OK;
}
Status DeQueue(SqQueue &Q,Student &s){
//如果队列不空,则删除Q的队头元素,用e返回其值,并返回OK
//如果队列为空,返回ERROR
if(Q.rear==Q.front) return ERROR;
s = Q.base[Q.front];
Q.front = (Q.front+1)%MAXSIZE;
return OK;
}
Status EmptyQueue(SqQueue Q){
//判断队列是是否为空,如果为空,返回TURE,否则返回FALSE
if(Q.front==Q.rear) return TURE;
else return FALSE;
}
void travelQueue(SqQueue Q){
//遍历打印Q中的元素
int p;
printf("队列中元素为:\n");
for(p=Q.front;(p+1)%MAXSIZE!=Q.rear;p=(p+1)%MAXSIZE){
printf("%d %s\n",Q.base[p].stuNo,Q.base[p].name);
}
printf("%d %s\n",Q.base[p].stuNo,Q.base[p].name);
printf("\n");
}
int main(){
SqQueue q;
InitQueue(q);
Student s;
strcpy(s.name,"");
srand(time(0));
for(int i=0;i<5;i++){
s.stuNo=rand()%100+1;
strcat(s.name,"a");
EnQueue(q,s);
}
travelQueue(q);
printf("出队:\n");
DeQueue(q,s);
travelQueue(q);
printf("入队:\n");
s.stuNo=rand()%100+1;
strcat(s.name,"a");
EnQueue(q,s);
travelQueue(q);
return 0;
}
还没有评论,来说两句吧...