C PROGRAM TO INSERT A NODE AT THE END OF A LINKED LIST

Sunny Bhaskar

11/9/20241 min read

#include <stdio.h>

#include <stdlib.h>

// Define the structure for a node

struct Node {

int data; // To store the data

struct Node* next; // Pointer to the next node

};

// Function to add a new node at the end

void addNodeAtEnd(struct Node** head_ref, int new_data) {

// Allocate memory for the new node

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

struct Node* last = *head_ref; // Pointer to traverse to the last node

new_node->data = new_data; // Assign data to the new node

new_node->next = NULL; // Make the new node the last node

// If the linked list is empty, make the new node the head

if (*head_ref == NULL) {

*head_ref = new_node;

return;

}

// Traverse to the last node

while (last->next != NULL) {

last = last->next;

}

// Link the last node to the new node

last->next = new_node;

}

int main() {

// Creating an empty linked list

struct Node* head = NULL;

// Adding nodes to the linked list

addNodeAtEnd(&head, 10);

addNodeAtEnd(&head, 20);

addNodeAtEnd(&head, 30);

addNodeAtEnd(&head, 40); // Adding a new node with data 40

// Display the linked list

struct Node* temp = head;

printf("Linked list: ");

while (temp != NULL) {

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

temp = temp->next;

}

printf("NULL\n");

return 0;

}

Address

Prayagraj Phaphamau

Contacts

7518998334
sunnygamingyt298@gmail.com

Subscribe to our newsletter