How to implement linked list in C programming ?

This programs shows a simple way to implement singly link list ( Singly link list is the list which can be traversed only in one direction i.e. forward till end )

 $ vim simple_linked_list.c 
#include <stdio.h>
#include <stdlib.h>

struct node {
        int value;
        struct node *next;
};

void init_list(struct node *n, int value) {
        n->value = value;
        n->next = NULL;

}

void add_node(struct node *n, int value) {

        struct node *add = (struct node *) malloc(sizeof(struct node));
        add->value = value;
        add->next = NULL;

        while(n->next != NULL) {
                n = n->next;
        }

        n->next = add;

}

void print_list(struct node *n) {
        while(n->next != NULL) {
                printf("value: %d\n", n->value);
                n = n->next;
        }
        printf("value: %d\n", n->value);
}

int main(int argc, char **argv) {
        struct node *head;
        head = (struct node *)malloc(sizeof(struct node));
        init_list(head, 3);
        add_node(head, 2);
        add_node(head, 10);
        add_node(head, 21);
        add_node(head, 7);
        print_list(head);
}

The above program is self explanatory which initialises the head element of the linked list, adds more nodes into the linked list, and at the last prints the complete linked list.

The can be compiled as,

 $ gcc -o simple_linked_list simple_linked_list.c 
 $ ./simple_linked_list
value: 3
value: 2
value: 10
value: 21
value: 7
Follow Lynxbee

Leave a Reply / Ask Question