Saturday, January 14, 2023

Singly Linked List Insert at Specific Position or Insert in between

 Hello Students,

Today i am going to explain you Insert Node at Specific Position or Some time we say Insert Node in between

Insert at specific Position or insert at in-between both are same.

Function of Insert at specific Position or insert at in-between:

void insert_at_specific()
{
struct node *a=head;
int i,position;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\nEmter Number you want to add at specific position or in-between:");
scanf("%d",&newnode->data);
newnode->next=NULL;
printf("\nEnter Position where you want to add Node:");
scanf("%d",&position);
for(i=1;i<position-1; i++)
{a=a->next;}
newnode->next=a->next;
a->next=newnode;
}

Full Program for Insert in-between and insert at specific position:

#include<stdio.h>
#include<stdlib.h>
struct node{
int data;
struct node *next;
};
struct node *newnode,*head,*temp;

void create()
{int num,i;
printf("\nHow many nodes you want to create:");
scanf("%d",&num);
for(i=0; i<num; i++)
{
newnode=(struct node *)malloc(sizeof(struct node));
printf("\nEnter Data:");
scanf("%d",&newnode->data);
newnode->next=NULL;
if(head==NULL)
{head=temp=newnode;}
else
{temp->next=newnode;
temp=temp->next;
}}}
void insert_at_specific()
{
struct node *a=head;
int i,position;
newnode=(struct node*)malloc(sizeof(struct node));
printf("\nEmter Number you want to add at specific position or in-between:");
scanf("%d",&newnode->data);
newnode->next=NULL;
printf("\nEnter Position where you want to add Node:");
scanf("%d",&position);
for(i=1;i<position-1; i++)
{a=a->next;}
newnode->next=a->next;
a->next=newnode;
}


void display()
{
struct node *p;
p=head;
while(p->next!=NULL)
{
printf("%d->", p->data);
p=p->next;
}
printf("%d->",p->data);
}
void main()
{
    create();
    display();
    insert_at_specific();
    display();
    getch();
}

Output:





No comments: