diff options
| author | Gustav Sörnäs <gustav@sornas.net> | 2021-01-21 11:44:06 +0100 |
|---|---|---|
| committer | Gustav Sörnäs <gustav@sornas.net> | 2021-01-21 11:54:26 +0100 |
| commit | e5e6a8650a5ec4ef9ed73c9b7a31551258849f15 (patch) | |
| tree | bdf53ba8b28a0c9436b1ffb34ec1c8f0ed329d8c | |
| parent | 1287be831475f739fc3ab796945f9d72f18456f1 (diff) | |
| download | pintos-linked-list-e5e6a8650a5ec4ef9ed73c9b7a31551258849f15.tar.gz | |
implement the functions
| -rw-r--r-- | main.c | 61 |
1 files changed, 56 insertions, 5 deletions
@@ -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 { |
