Program in Java: To merge two linked list
import java.util.Scanner;
class node
{
int data;
node link;
node()
{
data=0;
link=null;
}
void AddEnd(int data)
{
node temp = new node();
temp.data=data;
if(this.data==0 && this.link==null)
{ //if the linkedlist is empty
this.data=data;
return;
}
else{
node ptr=this;
while(ptr.link!=null)
{
ptr=ptr.link;
}
ptr.link=temp;
}
}
void merge(node l) //node ptr is the linked list from which your are calling the merge function
{ //node l is the second linked list which stores takes another linked list object as parameter
//finally it combines the two list and stores in the memory
node ptr=this; //the memory
if(ptr==null) //if the ptr is null then make the node l and the new node chain
{
ptr=l;
}
else
{
while(ptr.link!=null)
{
ptr=ptr.link;
}
ptr.link=l;
}
}
void display()
{
node ptr=this; //stores the linkedlist
while(ptr.link!=null)
{
System.out.println(ptr.data);
ptr=ptr.link;
}
System.out.println(ptr.data);
}
public static void main(String args[])
{
node ob = new node();
ob.AddEnd(50);
ob.AddEnd(60);
ob.AddEnd(70);
System.out.println("First linked list is");
ob.display();
node ob2 = new node();
ob2.AddEnd(80);
ob2.AddEnd(90);
ob2.AddEnd(100);
System.out.println("Second linked list is");
ob2.display();
//combining the two list
ob.merge(ob2); //ob list will be at the first part of the chain and ob2 list will be at the second
//part of the chain
//so basically ob is ptr and ob2 is the l as defined in the merge()
System.out.println("Combined list is:");
ob.display();
}
}