C语言实现循环队列,精要版

#include <stdlib.h>
#include <stdio.h>
#define MAXSIZE 100
/*
written on 2018-5-28 14:23:12
this version doesn't have the full functions of queue
can't use it as the right version of the queue
*/

typedef int ElemType;
typedef struct{
    ElemType *data;
    int front;
    int rear;
}CQueue;

void init(CQueue *c){
    // 初始化
    c->data = malloc(sizeof(ElemType)*MAXSIZE);
    if (!c->data) exit(1);  // error, not allocation of memory
    c->front = 0; 
    c->rear = 0;
}

int length(CQueue c){
    return (c.rear - c.front + MAXSIZE)%MAXSIZE;
}

void enqueue(CQueue *c, ElemType e){
    // 入队,这里需要按断是不是队列已经满了,如果满了,则返回Error
    if ((c->rear+1)%MAXSIZE == c->front) exit(1); // full then error
    c->data[c->rear] = e;
    // c->rear ++; // this is the error version
    c->rear = (c->rear+1)%MAXSIZE;
}

void dequeue(CQueue *c, ElemType *e){
    // 需要判断队列是否为空
    if (c->rear == c->front) exit(1);  // empty, error
    *e = c->data[c->front];
    c->front = (c->front+1)%MAXSIZE;
}

void traverse(CQueue c){
    while(c.front!=c.rear){
        printf("Traverse: %d\n", c.data[c.front++]);
    }
}

void main(){
    CQueue c;
    init(&c);
    printf("***********TEST length***********\nsupposed: 0, actual:%d\n",length(c));
    enqueue(&c, 1);
    printf("***********TEST enqueue***********\nsupposed: 1, actual:\n");
    traverse(c);
    ElemType e;
    dequeue(&c, &e);
    printf("***********TEST dequeue***********\nsupposed: 0,1 actual:%d,%d\n", length(c), e);
}

/*
***********TEST length***********
supposed: 0, actual:0
***********TEST enqueue***********
supposed: 1, actual:
Traverse: 1
***********TEST dequeue***********
supposed: 0,1 actual:0,1
*/

©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

友情链接更多精彩内容