#include<stdio.h>
#include<stdlib.h>
struct node
{
int data;
struct node *next;
};
main()
{
struct node *start=NULL,*start1=NULL,*start2=NULL;
int n,m;
void create(struct node **, int);
void show(struct node *);
void merge(struct node *,struct node*,struct node**);
printf("\nEnter the number of elements you want in your first linked list :");
scanf("%d",&m);
create(&start,m);
printf("\nEnter the number of elements you want in your second linked list :");
scanf("%d",&n);
create(&start1,n);
merge(start,start1,&start2);
printf("\n first linked list is :\n");
show(start);
printf("\n second linked list is :\n");
show(start1);
printf("\n merged linked list is :\n");
show(start2);
getch();
}
void create(struct node **q,int n)
{
int i;
struct node *lst;
struct node *p;
lst=NULL;
printf("\nEnter the data only in increasing order :\n ");
for(i=1;i<=n;i++)
{
p=(struct node *)malloc(sizeof(struct node));
printf("\nEnter the %d element :",i);
scanf("%d",&(p->data));
p->next=NULL;
if(*q==NULL)
*q=p;
else
lst->next=p;
lst=p;
}
}
void show(struct node *start)
{
while(start!=NULL)
{
printf(" %d",start->data);
start=start->next;
}
}
void merge(struct node *start,struct node *start1,struct node **start2)
{
struct node *ptr1,*ptr2,*ptr3=NULL,*p,*lst;
ptr1=start;
ptr2=start1;
while(ptr1!=NULL&&ptr2!=NULL)
{
p=(struct node*)malloc(sizeof(struct node));
p->next=NULL;
if(ptr1->data<ptr2->data)
{
p->data=ptr1->data;
ptr1=ptr1->next;
}
else
{
p->data=ptr2->data;
ptr2=ptr2->next;
}
if(ptr3==NULL)
{
ptr3=p;
}
else
{
lst->next=p;
}
lst=p;
}
if(ptr1==NULL)
{
while(ptr2!=NULL)
{
p=(struct node*)malloc(sizeof(struct node));
p->next=NULL;
p->data=ptr2->data;
ptr2=ptr2->next;
if(ptr3==NULL)
{
ptr3=p;
}
else
{
lst->next=p;
}
lst=p;
}
}
else if(ptr2==NULL)
{
while(ptr1!=NULL)
{
p=(struct node*)malloc(sizeof(struct node));
p->next=NULL;
p->data=ptr1->data;
ptr1=ptr1->next;
if(ptr3==NULL)
{
ptr3=p;
}
else
{
lst->next=p;
}
lst=p;
}
}
*start2=ptr3;
}