这是我的 en_queue
函数,用于在不同条件下插入新元素。
void en_queue(int *queue,int max,int front,int rear)
{
int ch1;
printf("\n Enter element to add->");
scanf("%d",&ch1);
if(front==0 && rear==(max-1))
{
printf("\n Caution!! Queue Overflow!!");
}
else if(rear==(max-1) && front>0)
{
rear=0;
queue[rear]=ch1;
printf("\n %d added to the queue where front fo the queue has room but rear does not" ,ch1);
}
else if(front==-1 && rear==-1)
{
front=rear=0;
queue[rear]=ch1;
printf("\n %d added to the queue where this is the first element to the queue" ,ch1);
}
else
{
rear++;
queue[rear]=ch1;
printf("\n %d added to the queue where the element added in the rear" ,ch1);
}
}
这是我的 show_queue
函数。
void show_queue(int *newqueue,int front,int rear)
{
int i=0;
for(i=front;i<=rear;i++)
{
printf("%d",newqueue[i]);
}
}
通过打印语句,我检查元素总是被插入到第一个位置。所以,我最好的猜测是 rear
和 front
元素没有成功更新,但我找不到原因。另外,我至少应该通过 show_queue
函数看到正确插入的第一个值;相反,我看到的是垃圾值,但这些值是 constant 即。 4235968 每次。
更新-这是请求的主要功能。
#include<stdio.h>
#include<stdlib.h>
#define MAX 10
void en_queue(int *,int, int, int);
void show_queue(int *,int,int);
int main()
{
int queue[MAX],front=-1,rear=-1,ch;
do{
printf("\n <<Queue MENU>>");
printf("\n 1. Add Element");
printf("\n 2. Delete Element");
printf("\n 3. Show Queue");
printf("\n 4. Exit menu");
printf("\n Enter your choice->");
scanf("%d", &ch);
switch(ch)
{
case 1: en_queue(queue,MAX,front,rear);
break;
/*
case 2: del_queue(queue,MAX,front,rear);
break;
*/
case 3: printf("\n The queue is->");
show_queue(queue,front,rear);
break;
case 4:exit(0);
default: printf("\n Invalid Choice!!!");
return 0;
}
} while(ch!=4);
return 0;
}
最佳答案
您的front
和rear
是按值传递,因此它们的更改不会在此函数之外维护。
基本上发生的事情是你的 front
和 rear
变量是调用函数中存在的变量的副本,比如 主要
。因此,此处对其所做的更改不会反射(reflect)在调用函数中。
dequeue
也会遇到这个问题。
您可能想按照建议的相反顺序执行以下操作之一
- 使它们成为全局变量。 - 不推荐,风格不好,容易出错,只允许 1 个队列。
- 让它们成为父函数变量的指针
- OOP 风格,将队列做成一个
struct
,其中包含数组、max
、front
和rear
,并将其作为指针传递。
关于c - 元素未插入队列中的不同位置,值未正确显示,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18779337/