C PROGRAM TO INSERT A NODE AT THE FRONT 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 beginning
void addNodeAtFirst(struct Node** head_ref, int new_data) {
// Allocate memory for the new node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data; // Assign data to the new node
new_node->next = *head_ref; // Point the new node's next to the current head
*head_ref = new_node; // Make the new node the head
}
int main() {
// Creating an empty linked list
struct Node* head = NULL;
// Adding nodes at the beginning of the linked list
addNodeAtFirst(&head, 30); // New head with data 30
addNodeAtFirst(&head, 20); // New head with data 20
addNodeAtFirst(&head, 10); // New head with data 10
// Now, inserting node with data 40 at the front
addNodeAtFirst(&head, 40); // New head 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;
}