Reputation: 19
I'm having a issue on searching through a linked list. I'm making a grade book program and I'm doing input error checks to see if the user entered a existing course to enroll a student to said course.
So this is the struct for the course info with a doubly linked list.
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;
And their corresponding variables along with initialization.
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;
In this function I'm going to enroll a student to a course but first im going to do some input checking to make sure the course exist.
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");
}
}
The problem with what I currently have is that it only searches the first element of the linked list. How do I go about making a loop that checks the entire linked list?
Upvotes: 1
Views: 76
Reputation: 116
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);
Your problem is that you are not iterating over the list, rather you are only checking the list head. You need to maintain a pointer to the node you are checking and iterate it (point it to the next node) in case you didn't find what you were looking for. You exit if there is nothing left to search or you found what you were looking for.
Upvotes: 0
Reputation: 133567
Iterating a linked list is quite straightforward.
You need to use a local variable which is the current element of the list, which you init to Courses->Course_Head, eg:
Course* current = Courses->Course_Head;
then until current != NULL
you just keep updating the current to point to the next element, eg:
while (current != NULL) {
// do what your want with current
current = current->next;
}
Mind that in your example you speak about a doubly linked list but it's a single linked list with two pointers to head and tail, a double linked list has two pointers for each node in both directions so that you can traverse it in reverse order, which is not the case in your situation.
Upvotes: 1