Last active
December 17, 2015 15:29
-
-
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
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 <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