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

Add finished ex3

parent 111f876d
No related branches found
No related tags found
No related merge requests found
......@@ -8,6 +8,139 @@
#include <string.h>
#include <stdbool.h>
#define DEFAULT_CHAR_VALUE '0'
typedef struct _node {
int value;
struct _node* left;
struct _node* right;
} node;
typedef struct _linked_list {
char val;
struct _linked_list* next;
} list;
list* li_create() {
list* li = malloc(sizeof(li));
li->val = DEFAULT_CHAR_VALUE;
li->next = NULL;
return li;
}
list* li_create_with_value(char value) {
list* li = li_create();
li->val = value;
return li;
}
void li_destroy(list* li) {
list* current = li;
while (current != NULL) {
list *tmp = current;
current = current->next;
free(tmp);
}
}
void li_add(list* li, char value) {
if (li->val == DEFAULT_CHAR_VALUE) {
li->val = value;
return;
}
list *current = li;
while (current->next != NULL) {
current = current->next;
}
list *new = li_create_with_value(value);
current->next = new;
}
void li_print(list* li) {
if (li != NULL) {
li_print(li->next);
printf("%c, ", li->val);
}
}
node* node_create() {
node* nd = malloc(sizeof(node));
nd->value = 0;
nd->left = NULL;
nd->right = NULL;
return nd;
}
node* node_create_with_value(int value) {
node* nd = node_create();
nd->value = value;
return nd;
}
bool node_is_empty(node* nd) {
return (nd == NULL);
}
void node_destroy(node *nd) {
if (!node_is_empty(nd)) {
node_destroy(nd->left);
node_destroy(nd->right);
free(nd);
}
}
void node_add(node* nd, int value) {
if (!node_is_empty(nd)) {
if (value < nd->value) {
if (node_is_empty(nd->left)) {
node* new = node_create_with_value(value);
nd->left = new;
} else {
node_add(nd->left, value);
}
} else {
if (node_is_empty(nd->right)) {
node* new = node_create_with_value(value);
nd->right = new;
} else {
node_add(nd->right, value);
}
}
}
}
void search_path(node* nd, int value, list* l) {
if (node_is_empty(nd)) {
return NULL;
}
if (nd->value == value) {
li_print(l);
}
if (value < nd->value) {
li_add(l, 'g');
search_path(nd->left, value, l);
} else if (value > nd->value) {
li_add(l, 'd');
search_path(nd->right, value, l);
}
}
int main() {
list* li = li_create();
node* tree = node_create_with_value(10);
node_add(tree, 0);
node_add(tree, 20);
node_add(tree, -5);
node_add(tree, 5);
node_add(tree, 15);
node_add(tree, 25);
node_add(tree, 22);
node_add(tree, 24);
search_path(tree, 24, li);
printf("\n");
node_destroy(tree);
return EXIT_SUCCESS;
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Please register or to comment