上一篇是队列的链式存储,以下是另外一种链式存储的时候,使用了几个c++语言的关键字,代码如下:
struct Fifo {
int front;
int rear;
int **tab;
int size;
};
//初始化队列
void init(struct Fifo * fifo, int size) {
fifo->size = size;
fifo->tab = new int*[size];
fifo->front = 0;
fifo->rear = 0;
}
//是否为空
bool isEmpty(struct Fifo* fifo) {
return (fifo->front == fifo->rear);
}
//进队(需要外部开辟内存)
int put(struct Fifo* fifo, int *value) {
fifo->tab[fifo->rear] = value;
fifo->rear = (fifo->rear + 1) % fifo->size;
//队列长度自动扩展
if (fifo->rear % fifo->size == fifo->front) {
int **p = new int*[fifo->size * 2];
for (int i = 0; i < fifo->size; ++i) {
p[i] = fifo->tab[i];
}
//更新FIFO存储element内存
delete []fifo->tab;
fifo->tab = p;
//队尾跳转到队尾的下一个位置
fifo->rear += fifo->size;
//更新队列长度
fifo->size *= 2;
}
return 0;
}
//出队(需要外部释放内存)
int get(struct Fifo* fifo, int **value) {
if (isEmpty(fifo)) {
return -1;
}
*value = fifo->tab[fifo->front];
fifo->front = (fifo->front + 1) % fifo->size;
return 0;
}
//获取队列中元素数量
int getLength(struct Fifo* fifo) {
return (fifo->front - fifo->rear + fifo->size) % fifo->size;
}
//销毁队列
void destroy(struct Fifo* fifo) {
delete [] fifo->tab;
}