#include <stdio.h>
#include <malloc.h>
#define MAXSIZE 10
/*
元素个数:(rear - front + maxsize)&maxsize
队列满:(rear + 1)%maxsize == front
下一个入队元素位置:(rear + 1)%maxsize
下一个出队元素位置:(front + 1)%maxsize
队列为空:front == rear
-----------------只有rear指针的情况下:----------
对头为: (Rear + Maxsize - Length) % Maxsize
队列满: (Rear + 1) % Maxsize == (Rear + Maxsize - Length) % Maxsize
队列空: (Rear + Maxsize - Length) % Maxsize == rear
*/
typedef char ElemType;
typedef struct Queue{
ElemType data[MAXSIZE];
int length;
int rear;
}Queue;
bool InitQueue(Queue &Q){
Q.data = (ElemType*)malloc(sizeof(ElemType) * MAXSIZE);
if(!Q.data) return false;
length = 0;
rear = 0;
return true;
}
bool Enqueue(Queue &Q, ElemType e){
if((Q.rear + 1)%MAXSIZE == (Q.rear + MAXSIZE - Q.length)%MAXSIZE) return false;
Q.data[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXSIZE;
Q.length++;
return true;
}
bool DeQueue(Queue &Q, ElemType &e){
if((Q.rear + MAXSIZE - Q.length)%MAXSIZE == Q.rear){
return false;
}
e = Q.data[(Q.rear + MAXSIZE - Q.length)%MAXSIZE];
Q.length--;
return true;
}
只有rear指针的环形循环队列
最新推荐文章于 2022-12-11 17:28:52 发布