C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Dynamic Memory Allocation in C

Linked list creation with malloc() function

C Program: Linked list creation with malloc() function

C

#include <stdio.h>

#include <stdlib.h>

 

struct Node {

    int data;

    struct Node *next;

};

 

int main() {

    struct Node *head = NULL, *newNode, *temp;

    int n, i;

 

    // Step 1: Input number of nodes

    printf("Enter the number of nodes: ");

    scanf("%d", &n);

 

    // Step 2: Create linked list using malloc()

    for (i = 0; i < n; i++) {

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

        if (newNode == NULL) {

            printf("Memory allocation failed!\n");

            return 1;

        }

 

        printf("Enter data for node %d: ", i + 1);

        scanf("%d", &newNode->data);

        newNode->next = NULL;

 

        // Attach new node to list

        if (head == NULL)

            head = newNode;  // First node

        else {

            temp = head;

            while (temp->next != NULL)

                temp = temp->next;

            temp->next = newNode;

        }

    }

 

    // Step 3: Display the linked list

    printf("\nLinked List Elements: ");

    temp = head;

    while (temp != NULL) {

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

        temp = temp->next;

    }

    printf("NULL\n");

 

    // Step 4: Free allocated memory

    temp = head;

    while (temp != NULL) {

        struct Node *nextNode = temp->next;

        free(temp);

        temp = nextNode;

    }

 

    return 0;

}

Output

 
OUTPUT :
Enter the number of nodes: 3
Enter data for node 1: 10
Enter data for node 2: 20
Enter data for node 3: 30

Linked List Elements: 10 -> 20 -> 30 -> NULL


Explanation

Step

Description

struct Node

Defines a linked list node with data and next pointer.

malloc()

Allocates memory for each node dynamically.

head

Points to the first node of the list.

temp

Used for traversing the list and connecting new nodes.

free()

Releases the allocated memory at the end.