c - 需要帮助检查 C 中的链表

标签 c search linked-list

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

所以这是带有双向链表的类(class)信息结构。

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; 

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

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 你只是不断更新 current 指向下一个元素,例如:

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

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

关于c - 需要帮助检查 C 中的链表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32803896/

相关文章:

移位可以在 C 中添加 1 而不是零吗?以及如何避免呢?

c - 需要有关 fork 中 processIDs 的 2 个特定问题的帮助(在类似 unix 的系统上)-C 语言

c - C中空格的转义序列是什么?

Android 搜索对话框未出现

linux - 查看当前登录的人并从/etc/passwd获取他们的信息

java - 从通用链表中删除所有重复项

c - C中的插入排序链表

c - 使用 MINGW 强制 C 将 stdin 读取为二进制

ajax - 保护Ajax查询的Solr服务器

c - C中的链表合并排序实现中丢失的节点