Merge sorted two linked list into a single list

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
struct node
{
int data;
struct node *next,*c;
}c;
struct node *insert(struct node *first,int data)
{
struct node *newnode=(struct node *)malloc(sizeof(struct node));
struct node *temp;
newnode->data=data;
newnode->next=NULL;
if(first==NULL)
{
first=newnode;
temp=first;
}
else
{
temp=first;
while(temp->next!=NULL)
{
temp=temp->next;
}
temp->next=newnode;
}
return temp;
}
void display(struct node *temp)
{
while(temp!=NULL)
{
printf("%d\n",temp->data);
temp=temp->next;
}
}
struct node * merge(struct node *a,struct node *b){
struct node *f=NULL;
 if(a ==  NULL)
        return b;
    else if(b == NULL)
        return a;
 if(a->data <= b->data){
         f = a;
        f->next = merge(a->next,b);
      }
else {
        f = b;
       f->next = merge(a,b->next);
      }
 return f;
}
main()
{
int n,n1,data;
puts("Enter Size Of first list");
scanf("%d",&n);
struct node *first=NULL;
puts("Enter elements  Of first list");
scanf("%d",&data);
n--;
first=insert(first,data);
while(n--)
{
scanf("%d",&data);
insert(first,data);
}
puts("Elements in First list");
display(first);
puts("Enter Size Of second list");
scanf("%d",&n1);
struct node *first1=NULL;
puts("Enter elements  Of second list");
n1--;
scanf("%d",&data);
first1=insert(first1,data);
while(n1--)
{
scanf("%d",&data);
insert(first1,data);
}
puts("Elements in second list");
display(first1);
puts("MERGING OF SORTED LIST");
struct node *c=merge(first,first1);
display(c);
}

Comments

Popular posts from this blog

How whatsapp works

Android N Developer Preview? It's exciting for most of you