Create a gist now

Instantly share code, notes, and snippets.

#include <stdio.h>
#include <stdlib.h>
struct node{
void* data;
struct node* next;
};
void set_int_value(struct node* node, int val)
{
// ptr->data est de type void*
int* i = malloc(sizeof (int));
*i = val;
node->data = i;
}
// Permet de créer une liste chainée {1,2,3}
struct node* create_list(int values[])
{
size_t node_size = sizeof (struct node);
struct node* current = malloc(node_size);
struct node* head = current;
for(int i = 0; i < 9; i++){
current->next = malloc(node_size);
set_int_value(current, values[i]);
current = current->next;
}
current->next = NULL;
set_int_value(current, values[9]);
return head;
}
void* fold(struct node* head, void* acc, void*(*fun)(void*, void*)){
struct node* current = head;
while(current){
acc = fun(acc, current->data);
current = current->next;
}
return acc;
}
void* add(void* a, void* b)
{
int* i = malloc(sizeof (int));
*i = *((int*)a) + *((int*)b);
return i;
}
void* multiply(void* a, void* b)
{
int* i = malloc(sizeof (int));
*i = *((int*)a) * *((int*)b);
return i;
}
void* sum(struct node* head)
{
int* seed = malloc(sizeof (int));
*seed = 0;
return fold(head, seed, add);
}
void map(struct node* head, void(*fun)(void*))
{
struct node* current = head;
while(current){
fun(current->data);
current = current->next;
}
}
void print_int(void* val)
{
printf("%d", *((int*)val));
}
void print_int_for_list(void* val)
{
printf("%d -> ", *((int*)val));
}
void print(struct node* head)
{
map(head, print_int_for_list);
printf("NULL\n");
}
void* count(struct node* head)
{
int* accumulator = malloc(sizeof (int));
struct node* current = head;
while(current){
current = current->next;
(*accumulator)++;
}
return accumulator;
}
void* value_at(struct node* head, int index)
{
struct node* current = head;
int* length = malloc(sizeof (int));
length = ((int*)count(head));
if(index < *length){
for(int x = 0; x < (index - 1); x++){
current = current->next;
}
}
return current->data;
}
int main(void)
{
int values[10] = {1,2,3,4,5,6,7,8,9,10};
struct node* l = create_list(values);
print(l);
print_int(sum(l));
printf("\n");
print_int(value_at(l, 6));
printf("\n");
}
@Veejay
Owner
Veejay commented Sep 2, 2011

Un truc que je ne comprends pas trop : je comptais passer un tableau à la fonction qui crée la liste chainée pour les valeurs des cellules, mais apparemment déterminer la taille du tableau n'est pas aussi aisé que je l'aurais cru.

Connais-tu une bonne façon de gérer ce cas ? Si tu piges pas ce que je raconte on en reparle sur IRC.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment