循环队列里面的“出队列”其实就是头指针的移动,但是这样的话会出现问题就是,该部分的空间其实并没有被释放,那么以下情况中结果输出的队尾元素是本来应该已经“出队列”的数据。这是怎么回事呢?
#include<stdio.h>
#include<malloc.h>
#include<iostream>
using namespace std;
#define MAXQSIZE 6
#define ERROR -1
#define OK 1
typedef struct {
int* base;
int front;
int rear;
}SqQueue;
int InitQueue(SqQueue& Q)
{
Q.base = (int*)malloc(MAXQSIZE * sizeof(int));
if (!Q.base)return ERROR;
Q.front = Q.rear = 0;
return OK;
}
int QueueLength(SqQueue& Q)
{
return (Q.rear - Q.front + MAXQSIZE) % MAXQSIZE;
}
int EnQueue(SqQueue& Q, int e)
{
if ((Q.rear + 1) % MAXQSIZE == Q.front)return ERROR;
Q.base[Q.rear] = e;
Q.rear = (Q.rear + 1) % MAXQSIZE;
return OK;
}
int DeQueue(SqQueue& Q, int e)//出队
{
if (Q.front == Q.rear)return ERROR;
e = Q.base[Q.front];
Q.front = (Q.front + 1) % MAXQSIZE;
return OK;
}
int main()
{
SqQueue Q;
InitQueue(Q);
int e[3] = { 7,8,9 };
for (int i = 0; i < 3; i++)
{
EnQueue(Q, e[i]);
}
int m[2] = { 0 };
for (int i = 0; i < 2; i++)
{
DeQueue(Q, m[i]);
}
int n[4] = { 0,1,2,3 };
for (int i = 0; i < 4; i++)
{
EnQueue(Q, n[i]);
}
cout << Q.base[Q.front] << ' ' << Q.base[Q.rear] << endl;
}