循环队列

/*  队列是一种先进先出的线性表,具有线性表的特性:分为链式队列与顺序队列 
    顺序队列:用一段地址连续的存储单元存储数据元素,定义两个游标:指向队头 
    的游标(front)、指向队尾的游标(rear),如果front == rear队列为空,如果 
    (rear + 1) % MAXSIZE == front队列满(此为循环队列),如普通队列rear==MAXSIZE队列满 
*/  
  
#ifndef QUEUE_H  
#define QUEUE_H  
#define MAXSIZE 20  //队列的最大长度  
typedef int ElemType; //队列的数据类型  
typedef struct{  
    ElemType data[MAXSIZE]; //队列  
    int front; //队头的游标  
    int rear;  //队尾的游标  
}Queue;  
  
void InitQueue(Queue *q); //初始化队列  
  
void EnQueue(Queue *q,ElemType e); //元素e进队  
  
void DeQueue(Queue *q,ElemType *e); //队头的元素出队  
  
bool IsEmpty(Queue *q); //判断队列是否为空  
  
int GetQueueLength(Queue *q); //返回队列的长度  
  
void Clear(Queue *q); //清空队列  
  
void Print(Queue *q); //打印队列  
  



#include<stdio.h>
#include<stdlib.h>
#include "reQueue.h"

int main()  
{  
    Queue q;  
    InitQueue(&q);  
    for(int i = 1;i < 20;++i)  
        EnQueue(&q,i);  
    Print(&q);  
    int k;  
    DeQueue(&q,&k);  
    EnQueue(&q,30);  
    Print(&q);  
    return 0;  
}  

void InitQueue(Queue *q) //初始化队列  
{  
    q->front = q->rear = 0;  
}  
void EnQueue(Queue *q,ElemType e) //让元素e进队  
{  
    if((q->rear + 1) % MAXSIZE == q->front) //队列已满  
        return;  
    q->data[q->rear] = e; //元素e进队  
    q->rear = (q->rear + 1) % MAXSIZE; //游标rear上前进一位,如果已达最后,就移到前面  
}  
void DeQueue(Queue *q,ElemType *e) //队头的元素出队存入*e  
{  
    if(q->rear == q->front) //如果队列为空返回  
        return;  
    *e = q->data[q->front]; //返回队头的元素  
    q->front = (q->front + 1) % MAXSIZE; //游标front向前移一位,如果是队列的末尾移动到最前面  
}  
bool IsEmpty(Queue *q) //判断队列是否为空  
{  
    return q->front == q->rear ? true : false;  
}  
int GetQueueLength(Queue *q) //返回队列的长度  
{  
    return (q->rear - q->front + MAXSIZE) % MAXSIZE;  
}  
void Clear(Queue *q) //清空队列  
{  
    q->front = q->rear = 0;  
}  
void Print(Queue *q) //打印队列  
{  
    if(q->front == q->rear)  
        return;  
    else if(q->rear < q->front)  
    {  
        for(int i = q->front;i < MAXSIZE;++i)  
            printf("%d ",q->data[i]);  
        for(int j = 0;j < q->rear;++j)  
            printf("%d ",q->data[j]);  
        printf("\n");  
    }  
    else{  
        for(int i = q->front;i < q->rear;++i)  
            printf("%d ",q->data[i]);  
        printf("\n");  
    }  
}  






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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值