From e5e6a8650a5ec4ef9ed73c9b7a31551258849f15 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Gustav=20S=C3=B6rn=C3=A4s?= Date: Thu, 21 Jan 2021 11:44:06 +0100 Subject: implement the functions --- main.c | 61 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 56 insertions(+), 5 deletions(-) diff --git a/main.c b/main.c index c0273a4..ae9910b 100644 --- a/main.c +++ b/main.c @@ -35,21 +35,72 @@ int read_int() { return res; } -void insert (struct list *student_list) { +// Fetch a student name from the terminal input and add it to the list. +void insert(struct list *student_list) { + struct student *student = malloc(sizeof(struct student)); + char *name = read_input(); + if (!name) { + printf("Failed to read student name\n"); + free(student); + } else { + student->name = name; + printf("Inserted student with name '%s'\n", student->name); + list_push_front(student_list, &student->elem); + } } -void delete (struct list *student_list) { +// Get a student name from the terminal input, remove it from the list and +// deallocate the appropriate memory (if needed). +void delete(struct list *student_list) { + char *name = read_input(); + if (!name) { + printf("Failed to read student name\n"); + } else { + struct list_elem *e; + for (e = list_begin(student_list); e != list_end(student_list); + e = list_next(e)) + { + struct student *student = list_entry(e, struct student, elem); + if (strcmp(student->name, name) == 0) { + printf("Removing student '%s'\n", student->name); + list_remove(&student->elem); + free(student->name); + free(student); + break; + } + } + } + free(name); } -void list (struct list *student_list) { +// Print the entire list. +void list(struct list *student_list) { + struct list_elem *e; + for (e = list_begin(student_list); e != list_end(student_list); + e = list_next(e)) + { + struct student *student = list_entry(e, struct student, elem); + printf("Student: %s\n", student->name); + } } -void quit (struct list *student_list) { +// Clear the list and deallocate the memory. +void quit(struct list *student_list) { + struct list_elem *e; + struct student *student; + while (!list_empty(student_list)) { + e = list_pop_front(student_list); + student = list_entry(e, struct student, elem); + printf("Removing '%s'\n", student->name); + free(student->name); + free(student); + } + exit(0); } int main() { struct list student_list; - list_init (&student_list); + list_init(&student_list); int opt; do { -- cgit v1.2.1