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.

Related :   How to implement stack in C programming ?

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

lynxbee_ezoic

Subscribe with Valid Email Id to receive updates in Inbox. ( Secured by Google FeedBurner )

   


1 thought on “How to implement linked list in C programming ?”

Leave a Comment

Android Android Applications Android Build system Android Commands Application Libraries Application Stack / User Interface Bash / Shell Scripts Bluetooth driver Cloud Technologies Commands and Packages Compilation Content Management System Core Kernel C Programs Development & Build Development, Debugging and Performance Tools Development Environment Setup Django & REST Api Errors & Failures Git Hardware Platforms HTML JAVA Programs Linux, OS Concepts and Networking Linux Device Drivers Linux Host, Ubuntu, SysAdmin Linux Kernel Linux Networking Middleware Libraries, HAL Multimedia Audio, Video, Images NDK / Middleware / HAL OS Concepts PHP Programming Languages Scripting and Automation Search Engine Optimisation ( SEO ) Social Media Source Code Management ( SCM ) System Administration, Security Testing and Debugging Uncategorized Web design and development Website Hosting Wordpress Yocto / Bitbake / Openembedded