我正在尝试使用循环队列这种数据结构。
#include <stdio.h>
#include <stdlib.h>
enum boolean{
false,true
};
struct ArrayQueue{
int rare,front;
int capacity;
int *array;
};
struct ArrayQueue* CreateQueue(int cap)
{
struct ArrayQueue* queue;
queue = (struct ArrayQueue*)malloc(sizeof(struct ArrayQueue));
queue->rare = -1;
queue->front = -1;
queue->capacity = cap;
queue->array = (int*)malloc(sizeof(int)*queue->capacity);
int i;
for (i=0;i<queue->capacity;i++)
queue->array[i] = 0;
return(queue);
}
enum boolean isFull(struct ArrayQueue *queue)
{
return((queue->rare+1)%queue->capacity == queue->front);
}
enum boolean isEmpty(struct ArrayQueue *queue)
{
return(queue->front == -1);
}
int ElementsInQueue(struct ArrayQueue *queue)
{
return(((queue->capacity-queue->front)+queue->rare+1)%queue->capacity);
}
void En_queue(struct ArrayQueue *queue,int item)
{
if (isFull(queue) == false)
{
queue->rare = (queue->rare+1)%queue->capacity;
queue->array[queue->rare] = item;
if (queue->front == -1)
queue->front = queue->rare;
}
}
int De_queue(struct ArrayQueue *queue)
{
int data;
if (isEmpty(queue) == false)
{
data = queue->array[queue->front];
queue->array[queue->front] = 0;
if (queue->front == queue->rare)
{
queue->front = -1;
queue->rare = -1;
}
else
{
queue->front = queue->front+1%queue->capacity;
}
return data;
}
}
void Display(struct ArrayQueue *queue)
{
int i;
printf("\n Displaying the queue : \n");
for (i=0;i<queue->capacity;i++)
printf("%d ",queue->array[i]);
}
int main(void)
{
int cap,choice,item;
struct ArrayQueue *queue;
printf("\nEnter the Capacity of Queue: ");
scanf("%d",&cap);
queue = CreateQueue(cap);
while(1)
{
printf("\n\n");
printf("\n1.Enqueue");
printf("\n2.Dequeue");
printf("\n3.Display");
printf("\n4.Exit");
printf("\nEnter choice: ");
scanf("%d",&choice);
switch (choice)
{
case 1: if (isFull(queue) == true)
{
printf("\nQueue is Full..");
break;
}
else
{
printf("\nEnter a number: ");
scanf("%d",&item);
En_queue(queue,item);
Display(queue);
}
break;
case 2: if (isEmpty(queue)== true)
{
printf("\nQueue is Empty..");
break;
}
else
{
item = De_queue(queue);
printf("\nItem popped is: %d",item);
Display(queue);
}
break;
case 3: Display(queue);
break;
case 4: exit(0);
break;
}
}
}
它看起来一开始很完美,但是它有一些问题。
请看下面的截图
插入后
我的输入流是(根据此模式)...
- 进队
- 出队
- 显示
- 退出
{1,1,1,1,2,1,2,1,2,1,2,1,2,1}
|___|
here is the problem
- 当我输入2进行出列操作时,队列已满,但是没有任何东西被删除。输出的是一些垃圾值。
- 然后我输入1进行入列操作时,队列已满,但是它没有显示队列已满;相反,它要求我输入一个数字。
(由于我先进行了出列操作,所以我想先加入一个元素,然后再输入1选择入列操作,但是它又要求我输入一个数字。)
我无法找出错误。对于我的解释和奇怪的词汇,请原谅我。您可以尝试代码并给出输入流以查明问题吗?
提前感谢。
head
到rear
迭代,而不是从0
到capacity
。 - SHG