# 4 different inserations in linked list using C

posted May 5 3 min read

In this article,we will discuss four different types of insertion we can do in a linked list.In my previous article,  I have dicussed how to create linked list if you have not gone through yet then i request you to please go through that first.After that come to this blog for proper understanding.

These are following four different ways :

1. Insert a node at a very begining.
2. Insert a node at given index.
3. Insert a node at end.
4. Insert a node after some node.

# Code Logic

1. For node insertion at beginning, we need to point the node ptr(node to be inserted) to head and update the head to ptr.
2. For 2nd case,bring the pointer p before the element you want to insert in linked list.
3. For 3rd case, bring the pointer p last element.
4. For 4th case,just like other cases ptr is inserted after a node in a linked list.

# Code

``````#include <stdio.h>
#include <stdlib.h>
struct Node
{
int data;
struct Node *next; //self referencing node
};

{
while (ptr != NULL)
{
printf("Element:%d\n", ptr->data);
ptr = ptr->next;
}
}
//case 1
struct Node * insertionAtFirst(struct Node *head,int data){
struct Node *ptr=(struct Node *)malloc(sizeof(struct Node));
ptr->data=data;
return ptr;
}
//case 2
struct Node * insertionAtIndex(struct Node *head,int data,int index){
struct Node *ptr=(struct Node *)malloc(sizeof(struct Node));
int i=0;
while(i!=index){
p=p->next;
i++;
}
ptr->data=data;
ptr->next=p->next;
p->next=ptr;
}
//case 3
struct Node * insertAtEnd(struct Node *head,int data){
struct Node *ptr=(struct Node *)malloc(sizeof(struct Node));
ptr->data=data;
while(p->next!=NULL){
p=p->next;

}

p->next=ptr;
ptr->next=NULL;
}
//case 4
struct Node * insertAfterNode(struct Node *head,struct Node *prevNode,int data){
struct Node *ptr=(struct Node *)malloc(sizeof(struct Node));
ptr->data=data;

ptr->next=prevNode->next;
prevNode->next=ptr;
}
int main()
{

struct Node *second;
struct Node *third;
struct Node *fourth;
head = (struct Node *)malloc(sizeof(struct Node));
second = (struct Node *)malloc(sizeof(struct Node));
third = (struct Node *)malloc(sizeof(struct Node));
fourth = (struct Node *)malloc(sizeof(struct Node));

second->data = 20;
second->next = third;

third->data = 30;
third->next = fourth;

fourth->data = 40;
fourth->next = NULL;