【发布时间】:2022-01-12 23:17:49
【问题描述】:
#include <stdio.h>
# define MAX 3
int queue[MAX]; // array declaration
int front=-1;
int rear=-1;
// function to insert an element in a circular queue
void enqueue(int element)
{
if(front==-1 && rear==-1) // condition to check queue is empty
{
front=0;
rear=0;
queue[rear]=element;
}
else if((rear+1)%MAX==front) // condition to check queue is full
{
printf("Queue is overflow..");
}
else
{
rear=(rear+1)%MAX; // rear is incremented
queue[rear]=element; // assigning a value to the queue at the rear position.
}
}
// function to delete the element from the queue
int dequeue()
{
if((front==-1) && (rear==-1)) // condition to check queue is empty
{
printf("\nQueue is underflow..");
}
else if(front==rear)
{
printf("\nThe dequeued element is %d", queue[front]);
front=-1;
rear=-1;
}
else
{
printf("\nThe dequeued element is %d", queue[front]);
front=(front+1)%MAX;
}
}
// function to display the elements of a queue
void display()
{
int i=front;
if(front==-1 && rear==-1)
{
printf("\n Queue is empty..");
}
else
{
printf("\nElements in a Queue are :");
while(i<=rear)
{
printf("%d,", queue[i]);
i=(i+1)%MAX;
}
}
}
int main()
{
int choice=1,x; // variables declaration
while(choice<4 && choice!=0) // while loop
{
printf("\nPress 1: Insert an element");
printf("\nPress 2: Delete an element");
printf("\nPress 3: Display the element");
printf("\nEnter your choice");
scanf("%d", &choice);
switch(choice)
{
case 1:
printf("Enter the element which is to be inserted");
scanf("%d", &x);
enqueue(x);
break;
case 2:
dequeue();
break;
case 3:
display();
}}
return 0;
}
我的显示功能有问题,如果后部在某些情况下可能小于前部,我如何打印所有元素,例如在这段代码中,我尝试将 3 个元素 1、2、3 排入队列,然后将两个元素出列,我的意思是这里 1, 2 之后我再次尝试对两个元素 1,2 进行排队,最后当我尝试显示元素时,我什么也没得到,所以显示队列元素的完美方式是什么
【问题讨论】:
-
不相关:这个
# define max 3宏会造成无法估量的破坏。至少要大写# define MAX 3以避免意外将std::max之类的东西变成std::3 -
@user4581301 完成
-
while(i<=rear)应该是do ... while(i != (rear+1)%MAX) -
对@Azrael3000 观点的进一步解释:因为循环缓冲区环绕它很容易在后备数组中拥有比
front更早的rear。 -
好吧,我只能推荐你使用调试器并单步执行代码,这是一项重要的学习技能,将来会对你有很大帮助
标签: c++ data-structures