# Inserting a node after a given node in linked List

• Write a C program to add a node after a given node in linked list.

Given a singly linked list having N nodes, we have to add a new node after a given node of a linked list. Here we will write one customer functions "insertAfter" which adds a node after passed node of linked list..

Singly linked list's node structure is as follows:
```struct node {
int data;
struct node *next;
}
```

Algorithm to add a new node after a given node
We want to insert a new node after "previousNode";
• Dynamically create a new node using malloc function.
• Set data field of new node.
• Set the next pointer of new node to the next pointer of previousNode.
• Set next pointer of previousNode to new node.

## C program to insert a node after a given node in linked list

```#include <stdio.h>
#include <stdlib.h>

/* A structure of linked list node */
struct node {
int data;
struct node *next;

void initialize(){
}

/*
Given a Inserts a node in front of a singly linked list.
*/
void insert(int num) {
/* Create a new Linked List node */
struct node* newNode = (struct node*) malloc(sizeof(struct node));
newNode->data  = num;
/* Next pointer of new node will point to head node of linked list  */
/* make new node as new head of linked list */
printf("Inserted Element : %d\n", num);
}

void insertAfter(struct node* prevNode, int num) {
/* Input validation */
if (prevNode == NULL) {
printf("Error : Invalid node pointer !!!\n");
return;
}

/* creates a new node */
struct node* newNode =(struct node*) malloc(sizeof(struct node));
newNode->data  = num;
/* Set Next pointer of newNode to next pointer of nodePtr */
newNode->next = prevNode->next;
/* Set next pointer of prevNode to newNode */
prevNode->next = newNode;
}

/*
Prints a linked list from head node till tail node
*/
void printLinkedList(struct node *nodePtr) {
while (nodePtr != NULL) {
printf("%d", nodePtr->data);
nodePtr = nodePtr->next;
if(nodePtr != NULL)
printf("-->");
}
}

int main() {
initialize();
/* Creating a linked List*/
insert(2);
insert(4);
insert(5);
insert(9);
/* Inserting a node after third node(4) from head */
printf("\n\nAfter Insertion\n");
return 0;
}
```
Output
```Inserted Element : 2
Inserted Element : 4
Inserted Element : 5
Inserted Element : 9