Home Tutorial Datastructure Split a list into two equal size list

 
 

Share on Google+Share on Google+
Split a list into two equal size list
Posted on: May 4, 2010 at 12:00 AM
Advertisement
This tutorial demonstrate how to splits the list into two equal size list having same data inside.

Description:

In this example it has mainly three function one for inserting data into list another for printing the list and last one for split of list. 

Code:

# include <stdio.h>
# include <stdlib.h>
struct node
{
int data;
struct node *link;
};

void splitlist(struct node *p, struct node **q, int n)
     {
     	struct node *temp;
	int  i =1;
	temp = p;
	while( i < n)
	{
	 temp  =  temp->link;
	 i++;
	}
	*q = temp->link;
	temp->link  =  p;
	temp = *q;
		while(temp->link != p)
		temp = temp ->link;
		temp->link = *q;
	}


struct node *insertnode(struct node *p , int n)
{
struct node *temp;
 if(p==NULL)
	{
	p=(struct node *)malloc(sizeof(struct node));
		if(p==NULL)
		{
		printf("Error\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\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 values in the list are\n");
	 if(p!= NULL)
			do
			{
			printf("%d\t",temp->data);
			temp=temp->link;
			} while (temp!= p);

	 else
			printf("empty list\n");
 }

void main()
{
	int n,num;
	int x;
	struct node *start1 = NULL ;
	struct node *start2=NULL;
	printf("Enter the number of node for each splited list \n");
	scanf("%d",&n);
	num = n;
	n*=2; /* this is done to have data multiple of two
		so that it split into two equal parts. */
	while ( n-- > 0 )
	{
	printf( "\nEnter data to be placed in node\n");
	scanf("%d",&x);
	start1 = insertnode ( start1 , x );
	}
	printlist ( start1 );
	splitlist(start1,&start2,num);
	printf("\nFirst list is:\n");
	printlist(start1);
	printf("\nSecond list is:\n");
	printlist(start2);

}

Output:

Download this code

Advertisement

Related Tags for Split a list into two equal size 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 4, 2010

Recommend the tutorial

Advertisements Advertisements
 

 

 

DMCA.com