Skip to content

Instantly share code, notes, and snippets.

@derekerdmann
Last active December 17, 2015 15:29
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save derekerdmann/5632392 to your computer and use it in GitHub Desktop.
Save derekerdmann/5632392 to your computer and use it in GitHub Desktop.
Example of a linked list using void pointers rather than specified data types
#include <stdlib.h>
#include <stdio.h>
struct node {
void *data;
struct node* next;
};
/* Tack a value onto the end of the list, returning the head */
struct node *append(struct node *head, void *data) {
struct node *new_node = NULL;
if( !head ){
new_node = (struct node *) malloc( sizeof( struct node ) );
new_node->next = NULL;
new_node->data = data;
return new_node;
}
head->next = append( head->next, data );
return head;
}
/* Retrieve the data at the specified index */
void *get( struct node *head, int index ) {
if( index == 0 ) {
return head->data;
}
return get( head->next, index-1 );
}
/* Release memory used by the list */
void free_list( struct node *head ) {
if( head ){
free_list( head->next );
free( head );
}
}
int main() {
int values[] = { 1, 2, 3 };
struct node *list = NULL;
list = append( list, values );
list = append( list, &values[1] );
list = append( list, &values[2] );
/* Print the list we built */
int i;
for( i = 0; i < 3; i++ ){
printf("%d\n", *(int *) get(list, i));
}
free_list( list );
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment