C Programs | IT Developer
IT Developer

C Programs



Share with a Friend

Data Structures in C

Insert Node at End of Linked List

C Program: Insert Node at End of 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;

 

    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 insert a node at the end

struct Node* insertAtEnd(struct Node *head, int data) {

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

    struct Node *temp = head;

 

    if (newNode == NULL) {

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

        exit(0);

    }

 

    newNode->data = data;

    newNode->next = NULL;

 

    if (head == NULL) {

        head = newNode;

        return head;

    }

 

    while (temp->next != NULL)

        temp = temp->next;

 

    temp->next = newNode;

 

    return head;

}

 

// Function to display the 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, data;

 

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

    scanf("%d", &n);

 

    head = createList(n);

 

    printf("\nEnter data to insert at end: ");

    scanf("%d", &data);

 

    head = insertAtEnd(head, data);

 

    displayList(head);

 

    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

Enter data to insert at end: 40

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

Explanation

  1. createList() – Creates a linked list dynamically.
  2. insertAtEnd()
    • Allocates a new node.
    • Traverses to the last node.
    • Links the new node at the end.
  3. displayList() – Prints all the elements of the list.