Skip to content

@Veejay /gist:1187947
Created

Embed URL

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
#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

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
Something went wrong with that request. Please try again.