【数据结构】循环队列的实现

#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;
 }

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值