• 【数据结构】循环队列的一些函数


     1 #include <stdio.h>
     2 #include <stdlib.h>
     3 
     4 #define OK 1
     5 #define ERROR 0
     6 #define MAXQSIZE 10
     7 typedef int Status;   
     8 typedef int QElemType; //定义队列中元素类型
     9 
    10 typedef struct
    11 {
    12     QElemType *base;
    13     int front;
    14     int rear;
    15 }SqQueue;  //定义循环队列类型
    16 
    17 Status InitQueue(SqQueue & Q) ;//初始化为空队列,分配数组空间
    18 Status GetHead(SqQueue Q,QElemType &e) ;//获取队头元素的值并返回在e中
    19 Status EnQueue(SqQueue &Q,QElemType e);//队列非法,将元素e入队
    20 Status DeQueue(SqQueue &Q,QElemType &e);//队列非法,将元素e入队
    21 int QueueLength(SqQueue Q);//求队列的长度
    22 
    23 int main()
    24 {
    25     SqQueue Q;
    26     int m;
    27     QElemType e;
    28     InitQueue(Q);
    29     scanf("%d",&m);
    30     while(m!=0) //m=0表示操作结束
    31     {
    32         if(m==1) //m=1表示入队
    33         {
    34             scanf("%d",&e);
    35             EnQueue(Q,e);
    36         }
    37         else if(m==2)//m=2表示出队
    38         {
    39             DeQueue(Q,e);
    40         }
    41         scanf("%d",&m);
    42     }
    43     printf("length=%d
    ",QueueLength(Q));
    44     if (GetHead(Q,e)==OK)     
    45         printf("first=%d",e);
    46     else
    47         printf("first=NULL");
    48     return 0;
    49 }
    50 
    51 Status InitQueue(SqQueue & Q) //初始化为空队列,分配数组空间
    52 {
    53     Q.base=(QElemType *)malloc(sizeof(QElemType)*MAXQSIZE);
    54     if(!Q.base)
    55         return ERROR;
    56     Q.front=Q.rear=0;
    57     return OK;
    58 }
    59 
    60 Status GetHead(SqQueue Q,QElemType &e) //获取队头元素的值并返回在e中
    61 {
    62     if(Q.rear==Q.front) return ERROR;
    63     e=Q.base[Q.front];
    64     return OK;
    65 }
    66 
    67 Status EnQueue(SqQueue &Q,QElemType e)//队列非法,将元素e入队
    68 {
    69     if((Q.rear+1)%MAXQSIZE==Q.front) return ERROR;
    70     Q.base[Q.rear]=e;
    71     Q.rear=(Q.rear+1)%MAXQSIZE;
    72     return OK;
    73 }
    74 
    75 Status DeQueue(SqQueue &Q,QElemType &e)//队列非法,将元素出队
    76 {
    77     if(Q.rear==Q.front) return ERROR;
    78     e=Q.base[Q.front];
    79     Q.front=(Q.front+1)%MAXQSIZE;
    80     return OK;
    81 }
    82 
    83 int QueueLength(SqQueue Q)//求队列的长度
    84 {
    85     return (Q.rear-Q.front+MAXQSIZE)%MAXQSIZE;
    86 }
  • 相关阅读:
    Document
    Document
    Document
    Document
    Document
    Document
    手动版 轮播图
    Echarts tooltip 自定义formatter设置字体颜色
    CSS3中 translate、transform 和 translation 的区别和联系,及开发问题解决
    background 属性及遇到的问题
  • 原文地址:https://www.cnblogs.com/Zoeun/p/12705296.html
Copyright © 2020-2023  润新知