Question 1

Write a C/C++ program to perform the task of maintaining student information for 123 College. You are to use a linked-list for storing the student records. Each student record contains the studentís name and age, and it should be a node in the linked-list. Your program should have an insert(), delete(), and print() functions. The prototypes are given below:

void insert( struct student **headOfList, char *name, int age );
int delete( struct student **headOfList, char *name );
void print( struct student *headOfList );



The insert() function inserts the node in increasing alphabetical ordering.

Perform the following tasks in the main() function of your program:

1) Add the following 3 students to the linked-list (which is initially empty), one at a time:
a) John, 18
b) Sally, 19
c) Matt, 18
2) After adding the 3 students, print out the whole list using the print function.
3) Add the following student to the list, and print out the resulting list.
d) Jason, 18
4) Compute and print out the average age of the 4 students by traversing the linked-list.
5) Delete the student Matt from the list and print out the resulting list.

The print() function should output each of the studentsí name and age in a readable fashion. Make sure the output is properly formatted and each printing can be distinguished from the other.



MARKING CRITERIA

Program 1
- Insert() function
- Delete() function
- Print() function
- Main() function
- Output Format
- Formatting, variable names, comments, alignment
- Use of malloc()






(The function I follow the questions to do.)
Anyone can check for me,it is the function I did correct or not?

Answer :


#include <stdio.h>
#include <stdlib.h>


struct student{
char *name;
int age;
struct student *nextStudent;
};

void insert( struct node ** headOfList, char *name, int age ) {
struct student *newStudent = (struct student *)malloc( sizeof( struct student ) );
if (newStudent == NULL) {
printf( "Enter 3 students name: " );
return;
}
struct student * prevStudent = NULL;
struct student * currentStudent = *headOfList;
while (currentStudent != NULL) {
if (*name < currentStudent-> *name) {

break;
} else {

prevStudent = currentStudent;
currentStudent = currentStudent->nextStudent;
}
}

if (prevStudent == NULL) {

newStudent->*name = *name;
newStudent->nextStudent = *headOfList;
*headOfList = newStudent;
} else {
newStudent->*name = *name;
newStudent->nextStudent = currentStudent;
prevStudent->nextStudent = newStudent;
}
}

void print( struct student * headOfList ) {
struct student *currentStudent = headOfList;
while (currentStudent != NULL) {
printf( "Data in student is %c\n", currentStudent.data );
currentStudent = currentStudent->nextStudent;
}
printf("--------------------------------");
}


int main() {
struct Student *Head = NULL;

insert( &Head, 'John, 18' );

print( Head );

insert( &Head, 'Sally, 19' );

print( Head );

insert( &Head, 'matt, 18' );

print( Head );

return 0;
}