You are on page 1of 4

//merging of two sorted linked lists

#include<iostream>

using namespace std;

class node

public:

int data;

node *next;

};

void display(node *n);

int main()

int n;

cout<<"enter the no of node in the first linked list "<<endl;

cin>>n;

int a[n];

cout<<"enter the data in sorted form "<<endl;

cout<<"enter the data of the first linked list "<<endl;

for(int i=0;i<n;i++)

cin>>a[i];

node *first;

node *last;

node *temp;

first=new node();

first->data=a[0];

first->next=NULL;

last=first;

for(int i=1;i<n;i++)

{
temp=new node();

temp->data=a[i];

temp->next=NULL;

last->next=temp;

last=temp;

cout<<"display of first linked list"<<endl;

display(first);

int m;

cout<<"enter no of nodes of the second linked list "<<endl;

cin>>m;

int b[m];

cout<<"enter the data of the second linked list "<<endl;

for(int i=0;i<m;i++)

cin>>b[i];

node *second;

second=new node();

second->data=b[0];

second->next=NULL;

last=second;

for(int i=1;i<m;i++)

temp=new node();

temp->data=b[i];

temp->next=NULL;

last->next=temp;

last=temp;

cout<<"display of second linked list"<<endl;


display(second);

node *third;

if(first->data<second->data)

third=last=first;

first=first->next;

last->next=NULL;

else

third=last=second;

second=second->next;

last->next=NULL;

while(first && second)

if(first->data<second->data)

last->next=first;

last=first;

first=first->next;

last->next=NULL;

else

last->next=second;

last=second;

second=second->next;

last->next=NULL;

}
if(first)

last->next=first;

else

last->next=second;

cout<<"display of merge linked list "<<endl;

display(third);

void display(node *n)

while(n)

cout<<n->data<<" ";

n=n->next;

cout<<endl;

You might also like