Sunday, 24 December 2017

Write a program in C language to implement inserting a new node in a doubly linked list at any position.

Below is a picture of doubly linked list for your reference:
Implementation of the above problem in C language:
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
int data,c,i,n,pos;
struct node
{
int element;
struct node*next;
struct node*prev;
}*D=NULL;
void create(int);
void mbeg(void);
void display(void);
int count(void);
void main()
{
int ch;
while(1)
{
printf("\n\n1.Create\n");
printf("\n2.Insertion at any position\n");
printf("\n3.Display\n");
printf("\n4.Count\n");
printf("\n5.Exit\n");
printf("\nEnter your choice");
scanf("%d",&ch);
switch(ch)
{
case 1:
printf("\nEnter the no.of nodes");
scanf("%d",&n);
for(i=0;i<n;i++)
{
printf("\nEnter the element");
scanf("%d",&data);
create(data);
}
break;
case 2:
mbeg();
display();
break;
case 3:
display();
break;
case 4:
count();
break;
case 5:
exit(0);
break;
default: printf("\nWrong choice....");
}
}
}
void create(int data)
{
struct node *temp,*P;
temp=malloc(sizeof(struct node));
temp->element=data;
temp->next=NULL;
if(D==NULL)
{
temp->prev=NULL;
D=temp;
return;
}
P=D;
while(P->next!=NULL)
P=P->next;
temp->prev=P;
P->next=temp;
}
void display(void)
{
struct node *P,*temp;
if(D==NULL)
{
printf("List empty");
return;
}
P=D;
printf("\nThe Elements are :");
while(P!=NULL)
{
printf("\t%d->",P->element);
P=P->next;
}
}
void mbeg(void)
{
struct node *temp,*P;
int i,pos,data;
printf("\nEnter the element");
scanf("%d",&data);
printf("\nEnter the position of the element to be inserted");
scanf("%d",&pos);
if(D==NULL)
{
printf("\nList is empty");
return;
}
if(count()<pos)
{
printf("\nEnter a position less than a count %d",count());
return;
}
P=D;
temp=malloc(sizeof(struct node));
temp->element=data;
for(i=0;i<pos-1;i++)
{
P=P->next;
temp->next=P->next;
temp->prev=P;
P->next->prev=P;
P->next=temp;
printf("\n");
}
}
int count(void)
{
int c=0;
struct node *temp,*P;
if(D==NULL)
{
printf("\nThe list empty");
return 0;
}
P=D;
while(P!=NULL)
{
P=P->next;
c++;
}
printf("\nThe elements are is %d",c);
return c;
}


Thanks
Mukesh Rajput

No comments:

Post a Comment

Thanks
Mukesh Rajput