链表入队函数在C中只添加一个节点并覆盖前一个节点

n9vozmp4  于 2023-04-19  发布在  其他
关注(0)|答案(1)|浏览(93)

我的链表入队函数遇到了一个问题,每当我尝试入队多个节点时,它只添加一个节点并覆盖前一个节点。下面是该函数的代码:

void enqueue_w(student_info *CSC4352_queue, int *rear, w_list *w_queue, student_info ToEnqueue)
{
    // Allocate memory for the enqueued student
    node *added_student = (node *)malloc(sizeof(node));
    // Error handling
    if (added_student == NULL)
    {
        // If memory allocation fails, stop
        return;
    }
    // Set the new node to the student to enqueue
    added_student->student.ID = ToEnqueue.ID;
    strcpy(added_student->student.name, ToEnqueue.name);
    added_student->next = NULL;

    if (w_queue->front == NULL)
    {
        // If the queue is empty, the front and rear are set to the enqueued student node
        w_queue->front = w_queue->rear = added_student;
    }
    if (w_queue->front->next == NULL)
    {
        // If the queue only has one node, the next to the front is the added node
        w_queue->front->next = added_student;
        // The rear will become the new node
        w_queue->front = added_student;
    }
    else
    {
        // Else, we just enqueue the student after the rear
        w_queue->rear->next = added_student;
        // Then we set the rear to the added student node
        w_queue->rear = added_student;
    }
}

总的来说:

// Collecting the student's data
                printf("Enter your ID: ");
                scanf("%d", &ToEnqueue.ID);
                getchar();
                printf("\n");
                printf("Enter your name : ");
                fgets(ToEnqueue.name, 50, stdin);
                printf("\n");
                enqueue_w(CSC4352_queue, &rear, &w_queue, ToEnqueue);

我已经尝试修改代码以使用临时节点并正确分配指针,但我仍然遇到同样的问题。我也检查了我的输入值并确认它们是正确的。我怀疑可能存在内存分配或指针操作的问题,但我不确定。任何指导或建议将不胜感激。

gfttwv5a

gfttwv5a1#

问题已经找到并纠正,所以这不是答案。
下面说明了为什么尽量少写代码更好。
相关的OP代码(注解不影响发生的事情):

if (w_queue->front == NULL)
    {
        // If the queue is empty, the front and rear are set to the enqueued student node
        w_queue->front = w_queue->rear = added_student;
    }
    if (w_queue->front->next == NULL)
    {
        // If the queue only has one node, the next to the front is the added node
        w_queue->front->next = added_student;
        // The rear will become the new node
        w_queue->rear = added_student; // correction applied here
    }
    else
    {
        // Else, we just enqueue the student after the rear
        w_queue->rear->next = added_student;
        // Then we set the rear to the added student node
        w_queue->rear = added_student;
    }

而且,同样的功能用更少的代码行来表达:

// initiate or append to linked list
    if (w_queue->front == NULL)
        w_queue->rear = w_queue->front = added_student;
    else
        w_queue->rear = w_queue->rear->next = added_student;

力求代码清晰,而不是描述清晰。

相关问题