/* Program to split a linked list */
#include
#include
struct link
{
int info;
struct link *next;
};
typedef struct link node;
void create(node **ptr)
{
node *temp;
temp=*ptr;
char ch;
do
{
printf("Enter data : " );
scanf("%d",&temp->info);
printf("Want to add more ?(y/n) : ");
scanf("%s",&ch);
if(ch=='y')
{
temp->next=(node *)malloc(sizeof(node));
temp=temp->next;
}
} while(ch=='y');
temp->next=NULL;
}
void split(node **ptr1,node **ptr2,node **ptr3)
{
node *current1,*current2,*current3;
node *prev1,*prev2;
current1=*ptr1;
current2=*ptr2;
current3=*ptr3;
while(current1!=NULL)
{
prev1=current1;
current1=current1->next;
current2->info=prev1->info;
if(prev1->next->next==NULL)
{
current2->next=NULL;
prev2=current1;
current3->info=prev2->info;
current3->next=NULL;
break;
}
else
{
current2->next=(node *)malloc(sizeof(node));
current2=current2->next;
}
prev2=current1;
current1=current1->next;
current3->info=prev2->info;
if(prev2->next->next==NULL)
{
current3->next=NULL;
prev1=current1;
current2->info=prev1->info;
current2->next=NULL;
break;
}
else
{
current3->next=(node *)malloc(sizeof(node));
current3=current3->next;
}
}
}
void display(node *ptr)
{
while(ptr!=NULL)
{
printf(" %d --> ",ptr->info);
ptr=ptr->next;
}
printf("\b\b\b\b ");
}
main()
{
printf("\nProgram to split a linked list w.r.t alternative positions : \n");
node *head1,*head2,*head3;
head1=(node *)malloc(sizeof(node));
head2=(node *)malloc(sizeof(node));
head3=(node *)malloc(sizeof(node));
printf("\nEnter data to insert in linked list : \n");
create(&head1);
printf("\nBefore splitting : " );
display(head1);
split(&head1,&head2,&head3);
printf("\n\nAfter splitting : \n");
printf("\nLinked List 1 : ");
display(head2);
printf("\n\nLinked List 2 : ");
display(head3);
printf("\n\n\n");
}