C PROGRAM TO INSERT A NODE AT THE GIVEN POSITION 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;
struct Node* next;
};
// Function to add a new node at a specific position
void insertNodeAtPosition(struct Node** head_ref, int new_data, int position) {
// Allocate memory for the new node
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = NULL;
// If inserting at the head (position 0)
if (position == 0) {
new_node->next = *head_ref;
*head_ref = new_node;
return;
}
// Traverse to the node just before the position
struct Node* temp = *head_ref;
for (int i = 0; temp != NULL && i < position - 1; i++) {
temp = temp->next;
}
// If the position is greater than the number of nodes
if (temp == NULL) {
printf("Position is out of bounds.\n");
free(new_node);
return;
}
// Insert the new node at the given position
new_node->next = temp->next;
temp->next = new_node;
}
int main() {
// Creating an empty linked list
struct Node* head = NULL;
// Function to add a node at the beginning (for initial setup)
void addNodeAtFirst(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->next = *head_ref;
*head_ref = new_node;
}
// Adding some initial nodes
addNodeAtFirst(&head, 30);
addNodeAtFirst(&head, 20);
addNodeAtFirst(&head, 10);
// Inserting a node with data 40 at position 1
insertNodeAtPosition(&head, 40, 1);
// 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;
}