How can I use the doubly linked lists?

GTK+ FAQ
<<< Previous | About GLib | Next >>>

# How can I use the doubly linked lists?

The GList object is defined as:

    typedef struct _GList GList;

    struct _GList
    {
      gpointer data;
      GList *next;
      GList *prev;
    };

To use the GList objects, simply:

    GList   *list = NULL;
    GList   *listrunner;
    gint    array[] = { 1, 2, 3, 4, 5, 6 };
    gint    pos;
    gint    *value;

    /* add data to the list */
    for (pos=0;pos < sizeof array; pos++) {
      list = g_list_append(list, (gpointer)&array[pos]);
    }

    /* run through the list */
    listrunner = g_list_first(list);
    while (listrunner) {
      value = (gint *)listrunner->data;
      printf("%d\n", *value);
      listrunner = g_list_next(listrunner);
    }

    /* removing datas from the list */
    listrunner = g_list_first(list);
    list = g_list_remove_link(list, listrunner);
    list = g_list_remove(list, &array[4]);

The same code is usable with singly linked lists (GSList objects) by replacing g_list_* functions with the relevant g_slist_* ones (g_slist_append, g_slist_remove, ...). Just remember that since you can't go backward in a singly linked list, there is no g_slist_first function - you'll need to keep a reference on the first node of the list.

<<< Previous | Home | Next >>>
About GLib | Up | Memory does not seem to be released when I free the list nodes I've allocated