Double linked lists in C
This tutorial will deal with how to deal with double linked lists in C and will provide some code snippets for you to use.
At first you'll need of course a struct: struct element { struct element *prev; struct element *next; real data; } Your data will later be stored in the data var. Please change the type of this var to your needs.
The next step is to create a new list:
struct element *create ( real data ) {
struct element *new = malloc(sizeof(struct element));
new->data = data;;
new->prev = NULL;
new->next = NULL;
return new;
}
Now you can create a new list with:
list = create ( data );
After you've now a list with your first element, you'll maybe want to fill it with your values:
struct element *push ( struct element *list, real data ) {
struct element *new = malloc(sizeof(struct element));
new->data = data
new->prev = list;
new->next = NULL;
list->next = new;
return new;
}
After the end of the program you migth want to delete the last item of your list:
struct element *pop ( struct element *list ) {
list->prev->next = NULL;
struct element *new = list->prev;
free(list);
return new;
}
Please do not forget to free your memory!! If you forget this this will result in memory leaks in your program!!
Okay, now we've enough functions... here are some examples on how to use them:
void access_data ( struct element *list ) {
struct element *head = list;
struct element *current = head;
while ( current != NULL ) {
printf ("%f ",current->data);
current = current->next;
}
printf ("\n");
}
Fill a list with data:
void insert_data ( void ) {
real x = 0;
struct element *head;
struct element *current;
current = create ( x );
for (x = 1; x<=10; x++) {
current = push ( current, x );
}
}
Okay, I think this should be enough in order to work
successfully with double linked lists
Feel free to write me a
email /put me a note if you have proposals how to make this
tutorial even better! 