From 4848e9a1001bb0f4fd8748f73478a74c9261e5af Mon Sep 17 00:00:00 2001 From: "dario.genga" <dario.genga@etu.hesge.ch> Date: Tue, 25 Jan 2022 14:32:33 +0100 Subject: [PATCH] Add ex2 There is still a memory leak in row 16 and 103. --- ex2/ex2.c | 123 +++++++++++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 122 insertions(+), 1 deletion(-) diff --git a/ex2/ex2.c b/ex2/ex2.c index 6315611..d18b08e 100644 --- a/ex2/ex2.c +++ b/ex2/ex2.c @@ -6,8 +6,129 @@ #include <stdio.h> #include <stdlib.h> #include <string.h> -#include <stdbool.h> + +typedef struct list_t { + int *value; + struct list_t *next; +} list; + +list *create() { + list *li = malloc(sizeof(list)); + li->value = NULL; + li->next = NULL; + return li; +} + +void destroy(list *li) { + while (li != NULL) { + list *tmp = li; + li = li->next; + free(tmp); + } + free(li); + li = NULL; +} + +list *push(list *li, int *value) { + list *new = create(); + new->value = value; + new->next = li; + return new; +} + +list *push_at_index(list *li, int *value, int index) { + list *previous = NULL; + list *current = li; + int current_index = 0; + + // Search the list index + while (current_index < index && current != NULL) { + current_index++; + previous = current; + current = current->next; + } + + // Push the value at this index + list *new = create(); + new->value = value; + new->next = current; + if (previous != NULL) { + previous->next = new; + } else { + return new; + } + + return li; +} + +list *remove_from_index(list *li, int index) { + list *previous = NULL; + list *current = li; + int current_index = 0; + + // Search the list index + while (current_index < index && current != NULL) { + current_index++; + previous = current; + current = current->next; + } + + // Remove from index + if (current != NULL) { + if (previous != NULL) { + previous->next = current->next; + } else { + li = li->next; + } + free(current); + } + return li; +} + +void print(list *li) { + while (li != NULL && li->value) { + printf("%d ", *li->value); + li = li->next; + } + printf("\n"); +} int main() { + const int ARGUMENTS_COUNT = 6; + const int INSERT_INDEX = 4; + const int REMOVE_INDEX = 5; + int value_to_insert = 0; + int *array = malloc(sizeof(int) * ARGUMENTS_COUNT); + + list *li = create(); + + // Get the values + for (int i = 0; i < ARGUMENTS_COUNT; i++) { + int value; + scanf("%d", &value); + array[i] = value; + } + + // Execute the work + for (int i = 0; i < ARGUMENTS_COUNT; i++) { + if (i < 4) { + li = push(li, &array[i]); + if (i == 0) { + li->next = NULL; + } + } + else if (i == INSERT_INDEX) { + li = push_at_index(li, &value_to_insert, array[i]); + print(li); + } + else if (i == REMOVE_INDEX) { + li = remove_from_index(li, array[i]); + print(li); + } + } + + // Free the memory and exit the program + destroy(li); + free(array); return EXIT_SUCCESS; } -- GitLab