Skip to content
Snippets Groups Projects
Commit 4848e9a1 authored by dario.genga's avatar dario.genga
Browse files

Add ex2

There is still a memory leak in row 16 and 103.
parent 01e37c19
No related branches found
No related tags found
No related merge requests found
...@@ -6,8 +6,129 @@ ...@@ -6,8 +6,129 @@
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.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() { 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; return EXIT_SUCCESS;
} }
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment