C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Singly linked list creation

C Program: Singly linked list creation

C

#include <stdio.h>

#include <stdlib.h>

 

// Define structure for node

struct Node {

    int data;

    struct Node *next;

};

 

int main() {

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

    int n, i;

 

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

    scanf("%d", &n);

 

    if (n <= 0) {

        printf("Number of nodes should be greater than 0.\n");

        return 0;

    }

 

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

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

 

        if (newNode == NULL) {

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

            return 0;

        }

 

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

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

        newNode->next = NULL;

 

        if (head == NULL) {

            head = newNode;

            temp = head;

        } else {

            temp->next = newNode;

            temp = temp->next;

        }

    }

 

    // Display the linked list

    printf("\nLinked List Elements: ");

    temp = head;

    while (temp != NULL) {

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

        temp = temp->next;

    }

    printf("NULL\n");

 

    return 0;

}

Output

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

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

Program Explanation

  1. Structure Definition:

struct Node {

    int data;

    struct Node *next;

};

Each node has two parts —
data: stores integer value
next: pointer to the next node

  1. Dynamic Memory Allocation:
    Each node is created using:

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

  1. Linking Nodes:
    • The first node becomes the head.
    • For each subsequent node, the previous node’s next points to the new node.
  2. Traversal (Display):
    We start from head and keep printing data until next becomes NULL.