Tuesday, November 08, 2005

Linear linked list

This is how I implement linear linked lists in C. The structure must be defined in a header file.


In file list.h



#include <stdio.h>
#include <stdlib.h>

typedef char DATA; /* an element of type character */

struct linked_list{
        DATA d;
        struct linked_list *next;
);

typedef struct linked_list ELEMENT;
typedef ELEMENT *LINK;

Linear linked list includes some of the basic operations:


1. Create list
2. Count elements
3. Look up an element
4. Concatenate lists
5. Insert an element
5. Delete an element


Here is how I create a list by recursion.



#include "list.h"

LINK string_to_list(char s[])
{
        LINK head;

        if (s[0] == '\0') /* base case */

                return NULL;

        else {
                head = malloc(sizeof(ELEMENT));
                head -> d = s[0];
                head -> next = string_to_list(s+1);
                return head;
        }
}

No comments: