Thursday, 27 March 2014

MERGING OF TWO LINKED LIST

QUES=>Two linked lists are given as
       A: 1, 2, 3, 4, 5, 6
 B:  7, 8, 9, 10, 11, 12
Make a third linked list so that it is in the following order.

 C: 1,7,2,8,…..,6,12


                                           CODE

#include<stdio.h>
#include<conio.h>
#include<malloc.h>
typedef struct nodetype
{  int info;
      struct nodetype *next;
}node;

void merg (node *head1, node *head2)
{
node *curr,*temp;
   curr=head1;
   temp=head1;
   while(head2!=NULL || head1!=NULL)
   {   head1=head1->next;
    curr->next=head2;
     head2=head2->next;
    curr->next->next=head1;


    curr=head1;
   }
   curr=NULL;
   puts("\nThe merged link list is :");
   while(temp!=NULL)
   {   printf(" %d ",temp->info);
       temp=temp->next;
   }

}


void main()
{  node *head1,*head2,*ptr1,*ptr2,*p,*q,*h1,*h2;
int i,j;
   clrscr();
   ptr1=(node*)malloc(sizeof(node));
   ptr2=(node*)malloc(sizeof(node));
   head1=ptr1;
   head2=ptr2;
   h1=ptr1;
   h2=ptr2;
   ptr1->info=1;
   ptr2->info=7;

   for(i=2,j=8; i<=6,j<=12; i++,j++)
   { p=(node*)malloc(sizeof(node));
     q=(node*)malloc(sizeof(node));
     p->info=i;
     q->info=j;

     ptr1->next=p;
 ptr1=ptr1->next ;

     ptr2->next=q;
 ptr2=ptr2->next ;


   }
   ptr1->next=NULL;
   ptr2->next=NULL;
printf("The link list is : ");
   while(head1!=NULL)
   {   printf(" %d ",head1->info);
       head1=head1->next;
   }
   printf("\nThe link list is : ");
   while(head2!=NULL)
   {   printf(" %d ",head2->info);
       head2=head2->next;
   }
   merg(h1,h2);
   getch();
   }


                                                   OUTPUT



No comments:

Post a Comment