Martin Broadhurst > Data Structures

Linked list

Contents

Description

A doubly-linked list allows efficient insertion at any position, and forward and backward traversal.

Creation

Create a list with MBlinkedlist_create.

Adding elements

Elements are added with MBlinkedlist_add_head, MBlinkedlist_add_tail, MBlinkedlist_insert_before, and MBlinkedlist_insert_after.

Removing elements

Elements are removed with MBlinkedlist_remove_head, MBlinkedlist_remove_tail and MBlinkedlist_remove.

Accessing elements

Iterate over the elements by following the nodes' next and previous pointers. The data elements are in the data field.

Example

#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;
}

Source code

Download

The following archives contain the full source code, example programs and build instructions for all of the data structures:

Links

Copyright (C) 2010 Martin Broadhurst