【发布时间】:2013-09-13 06:05:59
【问题描述】:
这是我的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 每次。
UPDATE-这里是要求的主要功能。
#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;
}
【问题讨论】:
-
您知道,当您更改
en_queue函数内的front和rear变量时,它只会更改该函数中的本地副本,而不是您在调用功能? -
@JoachimPileborg,啊!愚蠢的错误。我的错。我应该使用
pointers -
请在将来格式化您的问题时更加小心。不仅代码很难阅读,而且由于您从原始源中复制的所有制表符字符,也很难编辑。
-
@ChrisHayes,感谢您的编辑。我一定会的。 :)