我有一个代码,目的是将一个学生排队到一个课程的可用位置队列中。下面是我设计的函数:
int enqueue_CSC(student_info *CSC4352_queue, int *rear, student_info ToEnqueue)
{
// The status is used to determine if the student should be added to the waitlist
int status;
// We check if the queue is full
if (*rear == -1)
{
*rear = 0;
CSC4352_queue[*rear] = ToEnqueue;
status = 1;
}
if (*rear == 4)
{
printf("tThere are no seats available for the Big Data Analytics (CSC 4352) course.n");
printf("tYou will be added to the waiting list.n");
// status 0 means waitlist
status = 0;
return status;
}
// The queue is not full, increment the rear index and add the student;
CSC4352_queue[++(*rear)] = ToEnqueue;
// status 1 means successfully added
status = 1;
return status;
}
我的waitlist函数工作得很好,但是每当我尝试将一个学生加入课程队列时,他们就会在数组中被复制,例如:
输入:101084 John
打印队列:101084 John 101084 John
我已经调试了代码,我确定队列有重复,但是我不知道如何解决这个问题。
下面是打印函数:void print_CSC4352_queue(student_info *CSC4352_queue, int rear, int front)
{
printf("The content of the CSC 4352 queue is : n");
for (int i = 0; i < rear; i++)
{
printf("t Student ID : %dn", CSC4352_queue[i].ID);
printf("t Student name : %sn", CSC4352_queue[i].name);
printf("n");
}
return;
}
如果队列为空(我假设):
if (*rear == -1) {
*rear = 0;
CSC4352_queue[*rear] = ToEnqueue;
}
则在位置1第二次写入记录:
CSC4352_queue[++(*rear)] = ToEnqueue;
我没有测试你的代码片段的方法,但什么重新工作到这个?
#define STATUS_SUCCESS 1
#define STATUS_FAIL 0
#define EMPTY -1
#define CAPACITY 4
int enqueue_CSC(student_info *CSC4352_queue, int *rear, student_info ToEnqueue) {
if (*rear == CAPACITY) {
printf("tThere are no seats available for the Big Data Analytics (CSC 4352) course.n");
printf("tYou will be added to the waiting list.n");
return STATUS_FAIL;
}
*rear = *rear == EMPTY ? 0 : ++(*rear);
CSC4352_queue[*rear] = ToEnqueue;
return STATUS_SUCCESS;
}
如果你有选项交换状态值,只使用stdlib.h的EXIT_SUCCESS
和EXIT_FAILURE
代替。
如果将*rear
重新定义为下一个要写入数据的位置,则不需要为-1
设置特殊情况:
if(*rear + 1 == CAPACITY) {
// ...
}
CSC4352_queue[(*rear)++] = ToEnqueue;
// ...