Saturday, January 12, 2013

Alternatesplit THE LINK LIST


Q.)Alternatesplit THE GIVEN LINK LIST   and divide up its node to make two 
smaller lists. Element in the lists may be in any order.

for e.g-

list={1,2,3,4,5,6}
list1={1,3,5}
list2={2,4,6}

SOLUTION--


#include<stdio.h>
#include<stdlib.h>
struct node
{
    int data;
    struct node* next;
}*head;
int  main()
{
    struct node *temp;
    int num,i,item;
    scanf("%d",&num);
    //creation of link list//
    for(i=0;i<num;i++)
    {
        scanf("%d",&item);
        if(i==0)
        {
            head=malloc(sizeof(struct node));
            head->data=item;
            temp=head;
        }
        else
        {
            temp->next=malloc(sizeof(struct node));
            temp->next->data=item;
            temp=temp->next;
        }
    }
    temp->next=NULL;
    temp=head;
    struct node *head1,*head2,*temp1,*temp2;
    head1=NULL;
    head2=NULL;
    int flag=0;
    for(i=1;i<=num;i++)
    {
        if(flag==0)
        {
            if(head1==NULL)
            {
                head1=malloc(sizeof(struct node));
                head1->data=temp->data;
                temp1=head1;
            }
            else
            {
                temp1->next=malloc(sizeof(struct node));
                temp1->next->data=temp->data;
                temp1=temp1->next;
            }
            flag=1;
        }
        else if(flag==1)
        {
            if(head2==NULL)
            {
                head2=malloc(sizeof(struct node));
                head2->data=temp->data;
                temp2=head2;
            }
            else
            {
                temp2->next=malloc(sizeof(struct node));
                temp2->next->data=temp->data;
                temp2=temp2->next;
            }
            flag=0;
        }
        temp=temp->next;
    }
    temp1->next=NULL;
    temp2->next=NULL;
    printf("\nfirst list\n");
    temp1=head1;
    while(temp1!=NULL)
    {
        printf("%d ",temp1->data);
        temp1=temp1->next;
    }
    temp2=head2;
    printf("\nsecond list\n");
    while(temp2!=NULL)
    {
        printf("%d ",temp2->data);
        temp2=temp2->next;
    }
    return 0;
}


No comments:

Post a Comment