需要帮助检查C中的链接列表

问题描述:

我在通过链接列表进行搜索时遇到问题。我正在编写一个成绩簿程序,并且正在进行输入错误检查,以查看用户是否进入了现有课程,以便让学生参加该课程。需要帮助检查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"); 
    } 
} 

我现在的问题是它只搜索链表的第一个元素。我该如何做一个检查整个链表的循环?

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); 

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

迭代链表非常简单。

你需要使用一个局部变量是列表的当前元素,你要初始化课程 - > Course_Head,如:

Course* current = Courses->Course_Head; 

然后直到current != NULL只需保持更新当前指向下一个元素,如:

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

记住,在你的榜样,你谈论一个双向链表但它是一个单链表有两个指针头和尾,双链表有两个指针中的每个节点两个方向,让你可以tr厌恶它倒序,这是你的情况并非如此。

+0

对不起!所以如果我正确地理解它,一个双链表就是这样的。 struct Course_Info ** next? – Cheezdue

+0

是或简单地Course_Info * next,* prev; – Jack