Doubly Linked List


 

Doubly Linked List

This tutorial demonstrate how to implement doubly linked list.

This tutorial demonstrate how to implement doubly linked list.

Code:

# include <stdio.h>
# include <stdlib.h>
struct dnode
{
int data;
struct dnode *prev, *next;
};

struct dnode *insert(struct dnode *p , struct dnode **q, int n)
{
struct dnode *temp;

 if(p==NULL)
	{
		p=(struct dnode *)malloc(sizeof(struct dnode));
		if(p==NULL)
		{
		printf("Error Occurred\n");
		exit(0);
		}
		 p->data = n;
		 p-> prev = p->next =NULL;
		 *q =p;
	 }
	 else
	 {
	 temp =  (struct dnode *)malloc(sizeof(struct dnode));

	if(temp == NULL)
	{
		printf("Error Occurred\n");
		exit(0);
	}
		 temp->data = n;
		 temp->prev = (*q);
		 temp->next = NULL;
		 (*q)->next = temp;
		 (*q) = temp;
 }
	  return (p);
}

void printnode( struct dnode *p  )
{
	printf("All data of created list is\n");
	while (p!= NULL)
	{
		printf("%d\t",p-> data);
		p = p->next;
	}
}

void main()
{
	int n;
	int x;
	struct dnode *start = NULL ;
	struct dnode *end = NULL;
	printf("Enter the number of nodes to be created \n");
	scanf("%d",&n);
	while ( n-- > 0 )
	{
	printf( "Enter the data values for each node\n");
	scanf("%d",&x);
	start = insert ( start , &end,x );
	}
	printnode( start );
}

Output:

Download this code

Ads