C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Display linked list

C Program: Display linked list

C

#include <stdio.h>

#include <stdlib.h>

 

// Structure for a node

struct Node {

    int data;

    struct Node *next;

};

 

// Function to create linked list

struct Node* createList(int n) {

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

    int data, i;

 

    if (n <= 0) {

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

        return NULL;

    }

 

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

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

        if (newNode == NULL) {

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

            exit(0);

        }

 

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

        scanf("%d", &data);

        newNode->data = data;

        newNode->next = NULL;

 

        if (head == NULL) {

            head = newNode;

            temp = head;

        } else {

            temp->next = newNode;

            temp = temp->next;

        }

    }

 

    return head;

}

 

// Function to display linked list

void displayList(struct Node *head) {

    struct Node *temp = head;

 

    if (head == NULL) {

        printf("\nThe linked list is empty.\n");

        return;

    }

 

    printf("\nLinked List Elements: ");

    while (temp != NULL) {

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

        temp = temp->next;

    }

    printf("NULL\n");

}

 

int main() {

    struct Node *head = NULL;

    int n;

 

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

    scanf("%d", &n);

 

    head = createList(n);

 

    // Display the list

    displayList(head);

 

    return 0;

}

Output

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

Linked List Elements: 5 -> 10 -> 15 -> 20 -> NULL

Explanation

  1. struct Node – Defines each node with:
    • data: integer value
    • next: pointer to next node
  2. createList() – Dynamically allocates memory and links nodes together.
  3. displayList() – Traverses the linked list from head and prints each node until it reaches NULL.
  4. main() – Handles user input, creates the list, and displays it.