public
Created

  • Download Gist
gistfile1.c
C
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121
#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");
}

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.

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.