Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 4

Practical 14

Aim: Implement insertion of node at any position in liked list.

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

void create_list(int n);


void insert_node(int data,int position);
void display_list();
struct node
{
int data;
struct node *next;
}*head;

int main()
{
int n,data,position;
printf("Enter total number of node: ");
scanf("%d",&n);
create_list(n);
printf("\nData in the list: \n");
display_list();
printf("\nEnter data of the list: ");
scanf("%d",&data);
printf("Position= ");
scanf("%d",&position);
insert_node(data,position);
printf("\nData in the list: \n");
display_list();
getch();
return 0;
}
void create_list(int n)
{
int data,i;
struct node *newnode,*temp;
head=(struct node*)malloc(sizeof(struct node));
if(head==NULL)
{
printf("Unable to allocate memory");
}
else
{
printf("\nEnter the data of node 1: ");
scanf("%d",&data);
head->data=data;
head->next=NULL;
temp=head;
for(i=2;i<=n;i++)
{
newnode=(struct node*)malloc(sizeof(struct node));
if(newnode==NULL)
{
printf("Unable to allocate memory");
break;
}
else
{
printf("Enter the data of node %d: ",i);
scanf("%d",&data);
newnode->data=data;
newnode->next=NULL;
temp->next=newnode;
temp=temp->next;
}
}
printf("\nSingly linked list created successfully\n");
}
}
void insert_node(int data,int position)
{
int i;
struct node *newnode,*temp;
newnode=(struct node*)malloc(sizeof(struct node));
if(newnode==NULL)
{
printf("Unable to create memory");
}
else
{
newnode->data=data;
newnode->next=head;
temp=head;
for(i=2;i<=position-1;i++)
{
temp=temp->next;
if(temp==NULL)
break;
}
if(temp!=NULL)
{
newnode->next=temp->next;
temp->next=newnode;
printf("\nData inserted sucessfully\n");
}
else
{
printf("\nData not inserted sucessfully");
}
}
}
void display_list()
{
struct node *temp;
if(head==NULL)
{
printf("List is empty");
}
else
{
temp=head;
while(temp!=NULL)
{
printf("Data= %d\n",temp->data);
temp=temp->next;
}
}
}
Output:

You might also like