Linked list implementation in C

             It is a mostly used linear data structure in programming. Linked list has a collection of nodes and pointers. Pointers has the address of the next node. Node has the data. First node is called Head node. Last node has null pointer.

Let us implement the linked list with insertion operation.

Program:

#include <stdio.h>

#include <stdlib.h>

// creation of  the node structure

struct l_Node {

    int n_data;

    struct l_Node* next;

};

//create a new node

struct l_Node* createNode(int n_data) {

    struct l_Node* newNode = (struct l_Node*)malloc(sizeof(struct l_Node));

    if (!newNode) {

        printf("Memory is not allocated\n");

        exit(1);

    }

    newNode->n_data = n_data;

    newNode->next = NULL;

    return newNode;

}

// Insert the data at the beginning

void insertItBeginning(struct l_Node** head, int n_data) {

    struct l_Node* newNode = createNode(n_data);

    newNode->next = *head;

    *head = newNode;

}

// Insert the data at the end

void insertItEnd(struct l_Node** head, int n_data) {

    struct l_Node* newNode = createNode(n_data);

    if (*head == NULL) {

        *head = newNode;

        return;

    }

    struct l_Node* temp = *head;

    while (temp->next != NULL) {

        temp = temp->next;

    }

    temp->next = newNode;

}

// Print the data

void printIt(struct l_Node* head) {

    struct l_Node* temp = head;

    printf("Linked List: ");

    while (temp != NULL) {

        printf("%d -> ", temp->n_data);

        temp = temp->next;

    }

    printf("NULL\n");

}

int main() {

    struct l_Node* head = NULL;

    insertItBeginning(&head, 130);

    insertItEnd(&head, 210);

    insertItEnd(&head, 30);

    insertItBeginning(&head, 15);

    insertItEnd(&head,45);

    insertItBeginning(&head,34);

    printIt(head);

    return 0;

}

Output:

Linked List: 34 -> 15 -> 130 -> 210 -> 30 -> 45 -> NULL

The Linked list implementation in C was successful. This blog post covered the creation of Linked list,node and insertion in detail. Remaining parts are covered in next blog. Keep Coding!!!!

Comments

Popular posts from this blog

How to create a XML DTD for displaying student details

Symmetric Encryption in java

Java NIO examples to illustrate channels and buffers.