diff --git a/ex2/ex2.c b/ex2/ex2.c index 6315611067159e19d000230bfe97b122c5a270c1..d18b08efa9a1188f12faa7c57682da7afbc5ed2b 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; }