Home Tutorial Datastructure Circular Linked List

 
 

Share on Google+Share on Google+
Circular Linked List
Posted on: May 3, 2010 at 12:00 AM
Advertisement
This tutorial demonstrate how to implement circular linked list.

Description:

In the circular linked list the link of lat node is connected to the first node.

Code:

# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};
struct node *insert(struct node *p , int n)
{
struct node *temp;

 if(p==NULL)
	{
		p=(struct node *)malloc(sizeof(struct node));
		if(p==NULL)
		{
			printf("Error Occurred\n");
			exit(0);
		}
		 p-> data = n;
		 p-> link = p;
	 }
	 else
	 {
	temp = p;
	while (temp-> link != p)
	temp = temp-> link;
	temp-> link =  (struct node *)malloc(sizeof(struct node));
	if(temp -> link == NULL)
		{
		printf("Error Occurred\n");
		exit(0);
		}
		temp = temp-> link;
		temp-> data = n;
		temp-> link = p;
	  }
	  return (p);
}
void printlist ( struct node *p  )
{
		struct node *temp;
		temp = p;
		printf("The data in the list are :\n");
		if (p!= NULL)
		{  do
			{
			printf("%d\t",temp-> data);
			temp=temp->link;
			}while(temp!=p);
		}
		else
		printf("The link is empty \n");
}
void main()
{
	int num;
	int value;
	struct node *start = NULL ;
	printf("Enter the number of nodes to be created \n");
	scanf("%d",&num);
	while ( num-- > 0 )
	{
	printf( "Enter the data to be placed in a node\n");
	scanf("%d",&value);
	start = insert ( start , value );
	}
		printlist ( start );
}

Output:

Download this code

Advertisement

Related Tags for Circular Linked List:


Follow us on Twitter, or add us on Facebook or Google Plus to keep you updated with the recent trends of Java and other open source platforms.

Posted on: May 3, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com