需要帮助检查 C 中的链表

Need help checking a linked list in C

我在搜索链接列表时遇到问题。我正在制作一个成绩簿程序,并且正在检查输入错误,以查看用户是否输入了现有课程以注册学生参加该课程。

所以这是带有双向链表的课程信息结构。

typedef struct Course_Info // Course information
{
    int Course_ID;
    char Course_Name[15];
    struct Course_Info *next;
 } Course;

typedef struct // Linked list for Course
{
    int Ctracker; // Keeps track of courses
    Course *Course_Head;
    Course *Course_Tail;
} List_Course;

和它们对应的变量一起初始化。

 List_Student Students;
 List_Course Courses;
 Grade_List Grades;

 Students.Stracker = 0;
 Students.Student_Head = Students.Student_Tail = NULL;

 Courses.Ctracker = 0;
 Courses.Course_Head = Courses.Course_Tail = NULL;

 Grades.Grade_cnt = 0;
 Grades.Grade_Head = Grades.Grade_Tail = NULL; 

在这个函数中,我要为学生注册一门课程,但首先我要进行一些输入检查以确保该课程存在。

void EnrollStudent(List_Course *Courses, List_Student *Students)
{
    int CID; int SID;

    printf("Enter course ID: ");
    scanf("%d%*c", &CID);

    if( CID != Courses -> Course_Head -> Course_ID)
    {
        printf("Course does not exist!\n");
        return;
    }
    else
    {
        printf("Found class!\n");
    }
}

我目前的问题是它只搜索链表的第一个元素。我如何着手制作一个检查整个链表的循环?

迭代链表非常简单。

您需要使用一个局部变量,它是列表的当前元素,您将其初始化为 Courses->Course_Head,例如:

Course* current = Courses->Course_Head;

然后直到 current != NULL 你只是继续更新当前指向下一个元素,例如:

while (current != NULL) {
  // do what your want with current
  current = current->next;
}

请注意,在您的示例中,您谈论的是双向链表,但它是一个单链表,带有两个指向头和尾的指针,双链表在两个方向上的每个节点都有两个指针,因此您可以遍历它顺序相反,您的情况并非如此。

ListCourse * current = Courses->Course_Head;
while ( (NULL != current) && (CID != current->Course_ID) ) current = current->next;

if (NULL == current) printf("Course %d not found\n", CID);
else printf("Course %d found\n", CID);

你的问题是你没有遍历列表,而只是检查列表头。您需要维护一个指向您正在检查的节点的指针并对其进行迭代(将其指向下一个节点),以防您找不到您要查找的内容。如果没有任何内容可搜索或找到您要查找的内容,则退出。