Martin Broadhurst > Data Structures
A doubly-linked list allows efficient insertion at any position, and forward and backward traversal.
Create a list with MBlinkedlist_create.
Elements are added with MBlinkedlist_add_head, MBlinkedlist_add_tail, MBlinkedlist_insert_before, and MBlinkedlist_insert_after.
Elements are removed with MBlinkedlist_remove_head, MBlinkedlist_remove_tail and MBlinkedlist_remove.
Iterate over the elements by following the nodes' next and previous pointers. The data elements are in the data field.
#include <stdio.h>
#include <string.h>
#include <linkedlist.h>
int main(void)
{
MBlinkedlist * list = MBlinkedlist_create();
char * elements[] = {"A", "B", "C", "D", "E", "F"};
const unsigned int n = sizeof(elements) / sizeof(const char*);
unsigned int i;
MBlistnode * node;
unsigned int found = 0;
for (i = 0; i < n; i++) {
MBlinkedlist_add_tail(list, elements[i]);
}
for (node = list->head; node != NULL && !found; node = node->next) {
if (strcmp((const char*)node->data, "C") == 0) {
MBlinkedlist_insert_before(list, node, "X");
MBlinkedlist_insert_after(list, node, "Y");
found = 1;
}
}
for (node = list->head; node != NULL; node = node->next) {
printf("%s\n", (const char*)node->data);
}
putchar('\n');
for (node = list->tail; node != NULL; node = node->previous) {
printf("%s\n", (const char*)node->data);
}
MBlinkedlist_delete(list);
return 0;
}
The following archives contain the full source code, example programs and build instructions for all of the data structures:
Copyright (C) 2010 Martin Broadhurst