About

Kannur University btech CSE study materials, question papers, syllabus . . .

Thursday, July 4, 2013

S4- DSA LAB - MERGING OF TWO LINKED LIST

    /*           MERGING OF TWO LINKED LIST             */

import java.io.*;
class Node
{
int data;
Node next;
Node(int d)
{
data=d;
next=null;
}
void display()
{
System.out.println(data);
}
}
class List
{
DataInputStream nn=new DataInputStream(System.in);
Node first;
List()
{
first=null;
}
void inslast()
{
try
{
System.out.print("Enter the no      : ");
int d=Integer.parseInt(nn.readLine());
Node n=new Node(d);
Node curr=first;
if(first==null)
first=n;
else
{
while(curr.next!=null)
{
curr=curr.next;
}
curr.next=n;
}
}
catch(Exception e)
{}
}
void display()
{
Node curr=first;
if(first==null)
System.out.print("\nNo element present");
else
{
while(curr!=null)
{
curr.display();
curr=curr.next;
}}}

void mer(List n2)
{
Node c1=first;
Node c2=n2.first;
if(c1==null&&c2==null)
System.out.print("no element");
else
{
while(c1.next!=null)
{
c1=c1.next;}
c1.next=c2;
}}}

class mer
{
public static void main(String args[])throws Exception
{
DataInputStream get=new DataInputStream(System.in);
int p;
List n1=new List();
List n2=new List();
System.out.println("for first:");
do
{
System.out.println("1.ins_last\n2.Display");
System.out.print("Enter the choice  : ");
int ch=Integer.parseInt(get.readLine());
p=ch;
switch(ch)
{
case 1 : n1.inslast();break;
case 2 : n1.display();break;
}
}while(p<3);
System.out.println("\nfor second");
do
{
System.out.println("1.ins_last\n2.Display");
System.out.print("Enter the choice  : ");
int ch=Integer.parseInt(get.readLine());
p=ch;
switch(ch)
{
case 1 : n2.inslast();break;
case 2 : n2.display();break;
}
}while(p<3);
System.out.print("Merged list:  ");
n1.mer(n2);
n1.display();
}
}

OUTPUT

for first:
1.ins_last
2.Display
Enter the choice  : 1
Enter the no      : 1
1.ins_last
2.Display
Enter the choice  : 1
Enter the no      : 2
1.ins_last
2.Display
Enter the choice  : 1
Enter the no      : 3
1.ins_last
2.Display
Enter the choice  : 2
1
2
3
1.ins_last
2.Display
Enter the choice  : 3

for second
1.ins_last
2.Display
Enter the choice  : 1
Enter the no      : 4
1.ins_last
2.Display
Enter the choice  : 1
Enter the no      : 5
1.ins_last
2.Display
Enter the choice  : 2
4
5
1.ins_last
2.Display
Enter the choice  : 3
Merged list:
1
2
3
4
5





0 comments:

Post a Comment