DS – Merge 2 Linked Lists

#include<stdio.h>
#include<stdlib.h>
struct Node
{
            int data;
            struct Node *link;       
};
void merge();
void display();
struct Node *l1, *l2;
int main()
{
            struct Node *temp, *last;
            int ele;
            printf(“Enter List1 data(0 to stop) : “);
            while(1)
            {
                        scanf(“%d”, &ele);
                        if(ele==0)
                                    break;
                        else
                        {
                                    temp = (struct Node*)malloc(sizeof(struct Node));
                                    if(l1==NULL)
                                    {
                                                l1 = temp;
                                                last = temp;
                                    }
                                    else
                                    {
                                                last->link = temp;
                                                last = temp;    
                                    }
                        }
            }
            printf(“Enter List2 data(0 to stop) : “);
            while(1)
            {
                        scanf(“%d”, &ele);
                        if(ele==0)
                                    break;
                        else
                        {
                                    temp = (struct Node*)malloc(sizeof(struct Node));
                                    if(l2==NULL)
                                    {
                                                l2 = temp;
                                                last = temp;
                                    }
                                    else
                                    {
                                                last->link = temp;
                                                last = temp;    
                                    }
                        }
            }
            merge();
            display();         
            return 0;          
}
void merge()
{
            struct Node *p=l1;
            while(p->link)
            {
                        p=p->link;
            }
            p->link = l2;
}
void display()
{
            struct Node *temp=l1;
            printf(“L1 – Elements are : \n”);
            while(temp)
            {
                        printf(“%d \n”, temp->data);
                        temp = temp->link;    
            }
}
Scroll to Top