数据结构 通俗易懂版 c语言描述----队列(循环队列)及其基本操作

2022.2.9

循环队及其基本操作

(下一节 栈)

#include<stdio.h>
#include<malloc.h>
#include<stdbool.h>
#define ElemType int 

typedef struct Queue{
    ElemType *data;
    int head,rear;  
    int length,size;
}Queue;

//初始化
Queue * Init(int n){
    Queue *p=(Queue *)malloc(sizeof(Queue));
    p->head=0,p->rear=0,p->size=0,p->length=n;
    p->data=(ElemType *)malloc(sizeof(ElemType)*n);
    return p;
}

//判空
bool Empty(Queue *p){
    if(p->size==0)
        return true;
    else
        return false;
}

//返回队首元素
ElemType Front(Queue *p){
    if(p==NULL||p->size==0)return false;
    return p->data[p->head]; 
}

//val入队
bool push(Queue *p,int val){
    if(p==NULL)return false;
    if(p->size==p->length)return false;

    p->data[p->rear]=val;
    p->rear=(p->rear+1)%(p->length);
    p->size++;
    return true;
}

//出队
bool pop(Queue *p){
    if(p==NULL)return false;
    if(p->size==0)return false;

    p->head= (p->head+1)%(p->length);
    p->size--;
    return true;
}

//销毁队
bool Clear(Queue *p){
    if(p==NULL)return false;

    free(p->data);
    free(p);
    return true;
}

//输出队列元素
bool Output(Queue *p){
    printf("[-");
    for(int i=p->head,j=0;j<p->size;j++){
        printf("%d-",p->data[i]);
        i=(i+1)%(p->length);
    }
    printf("]\n");
}

int main(){
    Queue *p=Init(100);
    for(int i=0;i<55;i++){
        push(p,i);
    }
    Output(p);
    pop(p);
    Output(p);
    Clear(p);
    Output(p);
    return 0;
}

测试正确

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值