1. 数据元素的表示
#define MaxSize 10
typedef struct {
int data[MaxSize];
int front;
int rear;
}SqQueue;
2. 初始化队列
void InitQueue(SqQueue &Q) {
Q.front = Q.rear = 0;
}
3. 判断队空
bool QueueEmpty(SqQueue Q) {
return Q.rear == Q.front;
}
4. 入队操作
bool EnQueue(SqQueue& Q, int x) {
if ((Q.rear + 1) % MaxSize == Q.front) {
return false;
}
Q.data[Q.rear] = x;
Q.rear = (Q.rear + 1) % MaxSize;
return true;
}
5. 出队操作
bool DeQueue(SqQueue& Q, int& e) {
if (QueueEmpty(Q)) {
return false;
}
e = Q.data[Q.front];
Q.front = (Q.front + 1) % MaxSize;
return true;
}
6. 读取队首元素
bool GetFront(SqQueue Q, int& e) {
if (QueueEmpty(Q)) {
return false;
}
e = Q.data[Q.front];
return true;
}
7. 打印队列元素
void PrintQueue(SqQueue Q) {
printf("队列(由队首到队尾):");
if (QueueEmpty(Q)) {
printf("null\n");
return;
}
int front = Q.front;
while (front != Q.rear) {
printf("%d ", Q.data[front]);
front = (front + 1) % MaxSize;
}
printf("\n");
}
8. 验证代码
int main()
{
SqQueue q;
InitQueue(q);
PrintQueue(q);
for (int i = 1; i <= MaxSize-1; i++) {
EnQueue(q, i);
}
PrintQueue(q);
if (!EnQueue(q, MaxSize)) {
printf("进队失败,队列已满!\n");
PrintQueue(q);
}
int e = 0;
if (GetFront(q, e)) {
printf("读取成功,队首元素:%d\n", e);
}
for (int i = 1; i <= MaxSize - 1; i++) {
DeQueue(q, e);
}
printf("最后一个元素:%d\n", e);
PrintQueue(q);
if (!DeQueue(q, e)) {
printf("出队失败,队列为空!\n");
}
return 0;
}