Sunday, 1 April 2018

Insertion at mid in Doubly Linked List

If we gonna insertion at mid (at given position) then it is same as singly linked list but not that much simple. Basically, it will adjust the new element in such a way that previous node address and next node address will be hold by the same node.


#include<stdio.h>   /*input / output pre processor*/
#include<stdlib.h>  /*standard library function*/
#include<conio.h>  /*prototype*/
#include<malloc.h> /*dynamic memory allocation*/

struct node    /*structure of the node*/
{
struct node *pref;
int data;
struct node *ref;

};

void create(struct node **);   /*creation of the doubly linked list*/
void display(struct node *);   /*display the same*/
void addmid(struct node **);  /*insert element at the desirable positon*/

void main()
{
struct node *head=NULL;
int i,am,num;
clrscr();
printf("\nEnter no. of element for your node:- ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
create(&head);
}
printf("\nDo you want any insertion at mid(1--> Yes and 0--> No):- ");
scanf("%d",&am);
if(am==1)
{
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("\n\tEnter value:- ");
scanf("%d",&temp->data);
temp->pref=NULL;
temp->ref=NULL;
*q=temp;
}
else
{
r=(struct node *)malloc(sizeof(struct node ));
printf("\n\tEnter value:- ");
scanf("%d",&r->data);
while(temp->ref!=NULL)
{
temp=temp->ref;
}
r->ref=NULL;
r->pref=temp;
temp->ref=r;
}
}

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

void addmid(struct node **q)
{
struct node *temp, *r;
int i=2,j;
r=*q;
printf("\nEnter the position for the insertion:- ");
scanf("%d",&j);
while(i<j)
{
r=r->ref;
i++;
}
temp=(struct node *)malloc(sizeof(struct node));
printf("\n\tEnter value:- ");
scanf("%d",&temp->data);
temp->pref=r;
temp->ref=r->ref;
r->ref->pref=temp;
r->ref=temp;
}


No comments:

Post a Comment