Tuesday, 13 March 2018

Insertion at Middle in Singly Linked List

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

struct node
{
int data;
struct node *ref;
};

void create(struct node **);
void addmid(struct node **);
void display(struct node *);

void main()
{
struct node *head=NULL;
int i,num;
clrscr();
printf("\nEnter no. of elements for your node:- ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
create(&head);
}
addmid(&head);
display(head);
getch();
}

void create(struct node **q)
{
struct node *temp, *r;
temp=*q;
if(*q==NULL)
{
temp=(struct node *)malloc(sizeof(struct node));
printf("\nEnter value:- ");
scanf("%d",&temp->data);
temp->ref=NULL;
*q=temp;
}
else
{
r=(struct node *)malloc(sizeof(struct node));
printf("\nEnter value:- ");
scanf("%d",&r->data);
r->ref=NULL;
while(temp->ref!=NULL)
{
temp=temp->ref;
}
temp->ref=r;

}

}

void display(struct node *p)
{
while(p!=NULL)
{
printf("\nOUTPUT:- %d",p->data);
p=p->ref;
}
}

void addmid(struct node **q)
{
int i,position;
struct node *temp, *r;
r=(struct node *)malloc(sizeof(struct node));
if(r==NULL)
{
printf("\nUnable to allocate memory.");

}
else
{
printf("\nEnter the position:- ");
scanf("%d",&position);
printf("\n\nEnter value to be inserted at mid:- ");
scanf("%d",&r->data);
r->ref=NULL;
temp=*q;
for(i=2;i<=position-1;i++)
{
temp=temp->ref;
if(temp==NULL)
break;
}
if(temp!=NULL)
{
r->ref=temp->ref;
temp->ref=r;
printf("\nDATA INSERTED SUCCESSFULL");

}
else
{
printf("\nUNABLE TO INSERT DATA");
}
}
}


No comments:

Post a Comment