循环队列的基本操作及自动扩容
#define TRUE 1
#define FALSE 0
#define OK 1
#define ERROR 0
typedef int QElemType;
typedef int Status;
1.初始化队列
Status InitQueue(SqQueue * Q)
{
Q->queue_size = MAX_QUEUE_SIZE;
Q->base = malloc(Q->queue_size * sizeof(SqQueue));
if (!Q->base)
return ERROR;
Q->font = 0;
Q->rear = 0;
return OK;
}
2.入队操作
当rear的标号大于font的标号时,这时候扩容是非常简单的,直接使font+1即可
但是由于是循环队列,所以会出现rear的标号小于font的标号,此时如果直接将rear的标号+1,那么rear==font 这时候就会出现问题,
那么如何解决rear小于font这种情况呢
基本想法是这样的:将队列中的元素放到一个新的数组中,然后将数组的元素赋值给队列的头指针指向的数组,然后再将插入的元素放到这个队列中,这样队列就被重置为font大于rear的情况了,对于黑盒外的使用者而言只需要看到队列的特点(放入元素在队尾,删除元素在对头)即可。
代码如下:
Status EnQueue(SqQueue * Q, QElemType e)
{
if (!Q)
return ERROR;
if ((Q->rear + 1) % Q->queue_size == Q->font)
{
Q->queue_size = Q->queue_size + INCREMENT_SIZE;
Q->base = realloc(Q->base, sizeof(QElemType) * Q->queue_size);
if (!Q->base)
return ERROR;
if (Q->rear < Q->font)
{
int i = Q->font;
int j = 0;
int temp_A[Q->queue_size]; // hold the value of the queue
for (i; i != Q->rear; j++)
{
temp_A[j] = Q->base[i];
i = (i + 1) % (Q->queue_size - INCREMENT_SIZE);
}
// put the value of the array to the queue Q
for (int k = 0; k < (Q->queue_size-1-INCREMENT_SIZE); k++)
{
Q->base[k] = temp_A[k];
printf("Q: %d A: %d \n", Q->base[k], temp_A[k]);
}
// put the new elem to the queue
Q->base[Q->queue_size-1-INCREMENT_SIZE] = e;
Q->font = 0;
Q->rear = Q->queue_size-1;
return OK;
}
}
Q->base[Q->rear] = e;
Q->rear = (Q->rear+1) % Q->queue_size;
return OK;
}
3.出队操作
Status DeQueue(SqQueue * Q, QElemType * e)
{
if (!Q || (Q->font == Q->rear))
return ERROR;
*e = Q->base[Q->font];
Q->font = (Q->font + 1) % Q->queue_size;
return OK;
}
// If the queue is empty return true else return false
Status QueueEmpty(SqQueue * Q)
{
if (Q->font == Q->rear)
return TRUE;
else
return FALSE;
}
4.打印队列
Status printQueue(SqQueue * Q)
{
int status = TRUE;
if (!Q || (Q->font == Q->rear))
status = FALSE;
int index = Q->font;
int i = Q->font;
while ( i % Q->queue_size != Q->rear)
{
// printf(" array[%d] num %d \n", i, Q->base[index]); // 这里应该使用vist函数的,提高通用性
printf("\t num %d \n", Q->base[index]); // 这里应该使用vist函数的,提高通用性
i++;
index = (i) % Q->queue_size ;
}
return status;
}
PS:转载请注明出处!!!