Hey Guys my code is supposed to create a linked list of students and for each student, it has to create a linked list of grades for that student. I cant really tell if my two linked lists are set up properly, since no grades print when i try to traverse thru the lists.
struct Grade{
float score;
};
struct GradeNode{
Grade grade;
GradeNode *next_gnode;
};
struct StudentNode {
string name;
GradeNode *ghead;
StudentNode *next_snode;
};
StudentNode* head; //head of student linked list
the function below takes input from a file and makes a node with its value along with a pointer (ghead) to a linked list of grades, Set to null at first.
void buildStudentList(string n){
StudentNode *newNode{ new StudentNode}; //initialize new Student node
StudentNode *curr; //to traverse thru Student lIst
//initialize student node
newNode->name = n;
newNode->next_snode = nullptr;
//have HEAD of THIS student's grades set to null, since there are no grades present for this student at this moment
newNode->ghead = nullptr;
//if student list is empty
if(!head){
//make this student node the head of the list
head = newNode;
}
else{
//else add it to the end of the list
curr = head;
//traverse to the end of the list
while(curr->next_snode){
curr= curr->next_snode;
}
//make grades for this student
buildGradeList(newNode->ghead, newNode->name);
//assign new node to the end of the list
curr->next_snode = newNode;
}
};
build grade list function
//parameter is Grade Head, where we will attach a grade link list to it
void buildGradeList(GradeNode *head, string n){
//NOTE: head is HEAD OF GRADE LIST
bool quit = false;
int x;
while (!quit) {
cout<<"ENTER GRADE FOR "<<n<< ": (0 to quit)"<<endl;
cin>>x;
cout<<endl;
if(x==0){
//exit while loop and return //when one presses 0, they go to the next student on the list!!!
quit=true;
}
else{
//append this value to head
appendGrades(head, x);
}
}
//return to prev function
return;
}
appends grade to linked list, head is still ghead (head of grade list for this student)
void appendGrades(GradeNode *head, int s){
//create a new node with new score value
GradeNode *new_grade = {new GradeNode};
new_grade->grade.score = s;
new_grade->next_gnode = nullptr;
//node to traverse list
GradeNode *curr;
if(!head){
head = new_grade;
}else{
curr=head;
while (curr->next_gnode) {
curr= curr->next_gnode;
}
curr->next_gnode = new_grade;
}
};
Would appreciate any input, guys!
StudentNodehas thename, why doesn't theGradeNodehave thegrade? Seems like having a separateGradeclass is making it more complicated than it needs to be, or at least that there's two different approaches in the the same code.Studentdoesn't know that theLinkedListholding it even exists and can concentrate on representing Students--The Single Responsibility of SOLID) and B) allowsStudentto contain aLinkedList<Grade>member eliminating theGradeNodeclass and a lot of near-duplicate code.int, making sure that it works before adding the complication ofStudents andGrades.