Created
April 20, 2010 17:59
-
-
Save Veejay/372830 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#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_basic_list() | |
{ | |
size_t node_size = sizeof (struct node); | |
struct node* element1 = malloc(node_size); | |
struct node* element2 = malloc(node_size); | |
struct node* element3 = malloc(node_size); | |
element1->next = element2; | |
element2->next = element3; | |
element3->next = NULL; | |
set_int_value(element1, 1); | |
set_int_value(element2, 2); | |
set_int_value(element3, 3); | |
return element1; | |
} | |
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* 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\n", *((int*)val)); | |
} | |
void print(struct node* head) | |
{ | |
map(head, print_int); | |
} | |
int main(void) | |
{ | |
struct node* l = create_basic_list(); | |
print_int(sum(l)); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Je me demande si il est possible d'éviter les casts et certains void*