Skip to content

Instantly share code, notes, and snippets.

@SimoneCheng
Created November 30, 2024 14:42
Show Gist options
  • Save SimoneCheng/22361b9c6a3bac69959d37a2b0d97ba5 to your computer and use it in GitHub Desktop.
Save SimoneCheng/22361b9c6a3bac69959d37a2b0d97ba5 to your computer and use it in GitHub Desktop.
#include <stdio.h>
#include <stdlib.h>
typedef struct Student {
int studentID;
double GPA;
struct Student* next; /* problem 1-1 */
} Student_t;
void printStudentInfo(Student_t* current) {
while (current != NULL) {
printf("ID: %d, GPA: %2f\n", current->studentID, current->GPA);
current = current -> next;
}
}
Student_t* addStudent(Student_t* head, int studentID, double GPA) {
Student_t* newStudent = (Student_t*)malloc(sizeof(Student_t));
if (newStudent == NULL) { /* problem 1-2 */
printf("Memory allocation failed.\n");
exit(EXIT_FAILURE);
}
newStudent->studentID = studentID;
newStudent->GPA = GPA;
newStudent->next = head; /* problem 1-3 */
return newStudent;
}
void freeList(Student_t* head) {
Student_t* current;
while (head != NULL) {
current = current->next; /* problen 1-4 */
free(current);
head = head->next;
}
}
void main() {
Student_t* head = NULL; /* problem 1-5 */
head = addStudent(head, 112590001, 3.75);
head = addStudent(head, 112590025, 3.80);
head = addStudent(head, 112590011, 3.95);
printStudentInfo(head);
freeList(head);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment