循环队列

#include <stdio.h>
#include <stdlib.h>
//定义结构体
typedef struct {
    int *data;
    int capacity;
    int first;
    int last;
}Queue;
//创建队列
void Init(Queue *p, int capacity){
    capacity = p->capacity;
    p->data = (int *)malloc(sizeof(int)*capacity);
    p->first = 0;
    p->last = -1;
}
//入队
int Enter(Queue *p, int x) {
    if(p->last == -1){
        p->data[p->last + 1] = x;
        p->last++;
        return 1;
    }
    else if(p->first%5 == (p->last+1)%5)
        return -1;
    else{
        p->data[(p->last+1)%5] = x;
        p->last++;
        return 1;
    }
}
//出队
int Leave(Queue *p, int *px){
    if(p->last == -1)
        return -1;
    else{
        *px = p->data[p->first%5];
        p->first++;
        return 1;
    }
}
//输出队列
void Print(Queue *p){
    int i;
    for(i = p->first%5;i <= p->last%5;i++)
        printf("%d\n",p->data[i]);
}
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容