Split a linked list into two equal size list - DS TUTORIAL - onwnxcvnne
Headlines News :
Home » , , » Split a linked list into two equal size list - DS TUTORIAL

Split a linked list into two equal size list - DS TUTORIAL

Written By jomon on Monday 16 April 2012 | 09:07

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:

Share this article :

0 comments:

Speak up your mind

Tell us what you're thinking... !

 
Support : Creating Website | Johny Template | Mas Template
Copyright © 2011. onwnxcvnne - All Rights Reserved
Template Created by Creating Website Published by Mas Template
Proudly powered by Blogger