Tweet
/**
* This is a program of entering data in sorted order
* in a linked list & then traversing the list
* Programming Language : Java
*/
import java.io.*;
class node
{
protected int data;
protected node link;
public node()
{
data=0;
link=null;
}
public node(int d,node n)
{
data=d;
link=n;
}
public void setlink(node n)
{
link=n;
}
public void setdata(int d)
{
data=d;
}
public node getlink()
{
return link;
}
public int getdata()
{
return data;
}
}
class linkedlist
{
protected node start;
public linkedlist()
{
start=null;
}
public boolean isempty()
{
return start==null;
}
public void insert(int val)
{
node nptr=null,ptr=null,save=null;
boolean ins=false;
if(start==null)
start=nptr;
else if(val<=start.getdata())
{
nptr.setlink(start);
start=nptr;
}
else
{
save=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)
{
save.setlink(nptr);
}
}
}
public void traverse1()
{
node ptr=start;
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() + " |||| ");
System.out.println();
}
}
class traverse
{
protected static linkedlist T;
public static void main(String args[])
{
int n;
T=new linkedlist();
BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
for(int i=0;i<7;i++)
{
System.out.print("Enter data : ");
try
{
n=Integer.parseInt(br.readLine());
T.insert(n);
}
catch(Exception e)
{
System.out.println(e);
}
}
System.out.println("\nThe list is : ");
T.traverse1();
System.out.println();
}
}
Traversing a linked list in Java
Posted by
LAHAUL SETH
~
Traversing a linked list in Java
2012-02-08T10:02:00+05:30
LAHAUL SETH
Java
|
Comments
Traversing a linked list in Java
2012-02-08T10:02:00+05:30
LAHAUL SETH
Java
|