Doubly-Linked List in C

Since there wasn’t a good Linked List in C, I’ve created one. With a Linked List you can make dynamic array’s without throwing away memory. Normally you have to know the size of an array, but since this isn’t always known (for instance: if it depends on user input) it’s easier to use a Linked List.

It’s using the following concept (doubly linked) which is faster to add/edit/remove from a list:

How to create a list:

You will have to create a Header, this is the first element of the list, it’s the “start point” and “end point” of the list. You can create it like this:

struct CList *list;		// Will be the header
list = malloc(sizeof(struct CList));
CListCreate(list);

Now you can add values to the list (this can also be 32bits pointers). To add values, use the AddLast or AddFirst function:

CListAddLast(1, list);
CListAddLast(2, list);
CListAddLast(3, list);

You can iterate the list using the iterate function. It uses two variables to get it running. The first variable is used to store the current position of the iterator, and the second one is your return variable.

int iter = NULL;	// Empty iterator which stores the position of the iterator
struct CList *item;	// Empty pointer which will be filled using CListIterator
while(item = CListIterator(&iter, list))
{
	printf("val: %d ... \n", item->pointer);
}

To free the memory and destroy the list you can do this:

// Destroy list (and free it)
CListDestroy(list);
printf("size: %d ... \n", CListSize(list)); // Size should be 0
free(list);

Bugs?

Find them, fix them and store them in the comments 🙂

Download:

[ Download ]

Changelog:
– Removed “warnings” 07/01/2010 @ 14.30

Advertisements

One Response to Doubly-Linked List in C

  1. contrechoc says:

    Good! Credits earned!
    Could you make a small demo using this on the nds?
    For instance, making a linked list of structs of/around images adding and deleting these small images with the nds buttons 🙂
    contrechoc

Leave a Reply

Please log in using one of these methods to post your comment:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: