Sunday, 1 April 2018

Traverse in Doubly Linked List

Traverse in Doubly Linked List is as simple as Singly Linked List but here a narrow difference is that it will hold the address of previous node as well as the address of next node.
Their nothing more to remind just need to understand the logic and code will be simple as per your understanding.


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

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

void create(struct node **);   /*function for the creation of doubly linked list*/
void display(struct node *);   /*display the same*/

void main()
{
int i,num;
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);
}
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;
}
}


No comments:

Post a Comment