Skip to content

Instantly share code, notes, and snippets.

@gf3
Forked from Veejay/linked_list.c
Created Apr 20, 2010
Embed
What would you like to do?
Map in C
#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 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(l);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment