Sunday, 1 April 2018

Insertion at first in Doubly Linked List

Basically it's not a new thing that we gonna do , Today we will insert the element at first in Doubly linked list as simple as singly linked list. Nothing to do extra , except few changes.
So, here the code for the same.

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

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

void create(struct node **);  /*creates the doubly linked list*/
void display(struct node *);  /*display the same*/
void addfirst(struct node **); /*insert the element at first*/

void main()
{
int i,num,af;
struct node *head=NULL;
clrscr();
printf("\nEnter no. of element you want to insert:- ");
scanf("%d",&num);
for(i=0;i<num;i++)
{
create(&head);
}
printf("\nDo you want any insertion at first(1-->Yes and 0-->No):- ");
scanf("%d",&af);
if(af==1)
{
addfirst(&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;
}
temp->ref=r;
r->pref=temp;
r->ref=NULL;
}
}

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

void addfirst(struct node**q)
{
struct node *r;
r=(struct node *)malloc(sizeof(struct node));
printf("\n\tEnter value:- ");
scanf("%d",&r->data);
r->pref=NULL;
r->ref=*q;
*q=r;
}


No comments:

Post a Comment