Tweet
class node
{
protected int data;
protected node link;
public node() // default constructor
{
data=0;
link=null;
}
public node(int d,node n) // parametrized constructor
{
data=d;
link=n;
}
public void setlink(node n) // stores passed reference in link part
{
link=n;
}
public void setdata(int d) // stores passed value in data part
{
data=d;
}
public node getlink() // returns the link part
{
return link;
}
public int getdata() // returns the data part
{
return data;
}
}
class linkedlist
{
protected node start;
public linkedlist()
{
start=null;
}
public boolean isempty()
{
return start==null;
}
public void insert(int val) // insert a node in list pointed by start
{
node nptr,ptr,save=null;
nptr=new node(val,null);
boolean ins=false;
if(start==null)
start=nptr;
else if(val<=start.getdata()) // insert in the beginning
{
nptr.setlink(start); // set nptr i.e new node's link to start
start=nptr;
}
else
{
save=start; // insert in the middle or end of list
ptr=start.getlink();
while(ptr!=null)
{
if(val>=save.getdata() && val<=ptr.getdata())
{
save.setlink(nptr);
nptr.setlink(ptr);
ins=true;
break;
}
else
{
save=ptr;
ptr=ptr.getlink();
}
}
if(ins==false) // case of insertion in the end
save.setlink(nptr);
}
}
public void traverse()
{
node ptr=start;
System.out.println();
System.out.print(start.getdata()+ " --> ");
ptr=start.getlink();
while(ptr.getlink()!=null)
{
System.out.print(ptr.getdata()+ " --> ");
ptr=ptr.getlink();
}
System.out.print(ptr.getdata()+"!!!"); // last node's info
System.out.println();
}
public void concat(node l2) // concatenation function
{
node ptr,save=null;
save=ptr=start;
while(ptr!=null)
{
save=ptr;
ptr=ptr.getlink();
}
save.setlink(l2);
}
}
class linkjava1
{
protected static linkedlist l1,l2;
public static void main(String args[])
{
int num;
l1=new linkedlist();
l2=new linkedlist();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
System.out.println("....Starting Linked list for concatenation...");
System.out.println("....Enter 7 integers for list 1....");
for(int a=0;a<7;a++)
{
try
{
num=Integer.parseInt(br.readLine());
l1.insert(num);
}
catch(Exception e)
{
System.out.println(e);
}
}
System.out.println("\nList one : ");
l1.traverse();
System.out.println("....Enter 5 integers for list 2....");
for(int a=0;a<5;a++)
{
try
{
num=Integer.parseInt(br.readLine());
l2.insert(num);
}
catch(Exception e)
{
System.out.println(e);
}
}
System.out.println("\nList two : ");
l2.traverse();
l1.concat(l2.start);
System.out.println("\nConcatenated list : ");
l1.traverse();
}
}
import java.io.*;