This repository has been archived on 2026-05-11. You can view files and clone it. You cannot open issues or pull requests or push a commit.
Files
prog-104-p-02-2030/Chains_across_the_Island/Fundamentals/basics/basics.c
T
2026-04-02 00:31:53 +02:00

102 lines
1.8 KiB
C

#include "basics.h"
#include <stddef.h>
#include <stdlib.h>
struct list *list_append(struct list *l, int e)
{
if (!l) return NULL;
struct list *tmp = l;
struct list *new_node = calloc(1, sizeof(struct list));
if (!new_node) return NULL;
new_node->data = e;
if(!tmp) return new_node;
while (tmp->next) tmp = tmp->next;
tmp->next = new_node;
return l;
}
size_t list_count(struct list *l){
int nbr_nodes = 0;
if (!l) return nbr_nodes;
struct list *tmp = l;
//nbr_nodes ++;
while(tmp->next != NULL) {
nbr_nodes ++;
tmp = tmp->next;
}
return nbr_nodes;
}
int list_insert(struct list **l, size_t index, int e){
if(!l) return 1;
if (list_count(*l) < index) return 1;
struct list *new_node = malloc(sizeof(struct list));
if(!new_node) return 1;
new_node->data = e;
struct list *tmp = *l;
size_t ind = 0;
while(tmp != NULL && ind <index - 1){
tmp = tmp->next;
ind ++;
}
new_node->next = tmp->next;
tmp->next = new_node;
return 0;
}
struct list *list_get(struct list *l, size_t index){
if(!l) return NULL;
//if(list_count(l) < index) return NULL;
struct list *tmp = l;
size_t ind = 0;
while(tmp->next != NULL && ind != index){
tmp = tmp->next;
ind ++;
}
if(ind >= index) return NULL;
return tmp;
}
void list_destroy(struct list *l){
if (!l) return;
list_destroy(l->next);
free(l);
}
int main(void)
{
struct list *l = NULL;
l = list_append(l, 42); // l = [42] -> NULL
l = list_append(l, 7); // l = [7] -> [42] -> NULL
list_count(NULL); // 0
list_count(l); // 3
// Here, you should call "list_destroy(l);" when it will be implemented to
// prevent any memory leak
return 0;
}