50)Write a C program to merge to sorted singly linked list to interger into a third list such that third list is also in the sorted order.


#include<stdio.h>
#include<conio.h>
struct list
{
int data;
struct list *link;
};
typedef struct list NODE;
void disp(NODE *);
NODE *create(NODE *);
NODE *merge(NODE *,NODE *,NODE *);
void main()
{
NODE *list1=NULL,*list2=NULL,*list3=NULL;
clrscr();
list1=create(list1);
list2=create(list2);
list3=merge(list1,list2,list3);
printf(“\n\nFIRST LIST IS \n”);
disp(list1);
printf(“\n\nSECOND LIST IS \n”);
disp(list2);
printf(“\n\nTHIRD LIST IS \n”);
disp(list3);
getch();
}
NODE *create(NODE *list1)
{
int n,i,m;
NODE *tmp,*q;
printf(“\n\nHOW MANY NODES U WANT TO CREATE\n”);
scanf(“%d”,&n);
for(i=0;i<n;i++)
{
tmp=(NODE *) malloc(sizeof(NODE));
printf(“\n\nEnter the data \n”);
scanf(“%d”,&m);
tmp->data=m;
tmp->link=NULL;
if(list1==NULL)
{
list1=tmp;
}
else
{
q=list1;
while(q->link!=NULL)
{
q=q->link;
}
q->link=tmp;
}
}
return list1;
}
void disp(NODE *lis)
{
NODE *q;
q=lis;
while(q!=NULL)
{
printf(“%d->”,q->data);
q=q->link;
}
printf(“NULL”);
}
NODE *merge(NODE *l,NODE *p,NODE *r)
{
NODE *newnode,*k=r;

while(l && p)
{
newnode=(NODE *)malloc(sizeof(NODE));
newnode->link=NULL;
if(l->data<p->data)
{
newnode->data=l->data;
l=l->link;
}
else
{
newnode->data=p->data;
p=p->link;
}
if(r==NULL)
{
r=k=newnode;
}
else
{
k->link=newnode;
k=newnode;
}
}
if(l)
{
k->link=l;
}
if(p)
{
k->link=p;
}
return r;
}

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s