循环队列之顺序存储

循环队列判断 队列满 或 队列空

队空:Q.front == Q.rear

队满:(Q.rear+1)%MaxSize == Q.front

这种方法是空出一个存储为以易于辨别队空和队满。

#include<stdio.h>
#include<malloc.h>

#define INITSIZE 10

typedef int ElemType;

typedef struct{
    ElemType *base;
    int front;
    int rear;
    int length;
    int size;
}Queue;

void init(Queue *p){
    p->base = (ElemType *)malloc(INITSIZE*sizeof(ElemType));
    p->front = p->rear = 0;
    p->length = 0;
    p->size = INITSIZE;
}

void show(Queue *p){
    if(p->front == p->rear){
        printf("THE QUEUE IS EMPTY\n");
        return ;
    }
    int i = p->front;
    while(i != p->rear){
        printf("%2d",p->base[i]);
        i = (i+1)%p->size;
    }
    printf("\n");
}

void push(Queue *p, ElemType e){
    if((p->rear+1)%p->size == p->front){
        printf("THE QUEUE IS FILLED\n");
        return ;
    }
    p->base[p->rear] = e;
    p->rear = (p->rear+1) % p->size;
    p->length++;
}

void pop(Queue *p, ElemType *e){
    if(p->front == p->rear){
        printf("THE QUEUE IS EMPTY\n");
        return ;
    }
    *e= p->base[p->front];
    p->front = (p->front+1) % p->size;
    p->length--;
}

int main(){
    Queue queue;
    ElemType e;
    init(&queue);

    push(&queue,2);
    push(&queue,4);
    show(&queue);

    pop(&queue,&e);
    show(&queue);
    return 0;

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值