Home Tutorial Datastructure Doubly Linked List

 
 

Doubly Linked List
Posted on: May 1, 2010 at 12:00 AM
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

Related Tags for Doubly Linked List:


Ask Questions?

If you are facing any programming issue, such as compilation errors or not able to find the code you are looking for.

Ask your questions, our development team will try to give answers to your questions.