Tag Archives: Singly link list

Headless link list implementation in C

Singly link list

A link list is a non-linear data structure with a head pointer. The rest of the nodes in the list could be accessed by using “next” of head.

The code to create a list of N node involves creating head separately. Rest of the nodes are appended to the head.

That looked ugly to me and so I wrote it in a generic manner. Using a temporary pointer, I wrote a single loop to create N link list nodes, keeping head intact.

Here is the code:

#define NULL (char*)0

typedef struct node_ {
        int n;
        struct node_ *next;
} node;

int main()
        int i = 5;
        node *head = NULL;
        node *temp = NULL;

        while (i-- > 0) {
                head = malloc(sizeof(node));
                head->n = i;
                head->next = temp;
                temp = head;

        temp = head;