Sorted Linked List:
/**
* @author Abhinaw.Tripathi
*
*/
class Link
{
public long dData;
public Link next;
public Link(long dd)
{
dData=dd;
}
public void displayLink()
{
System.out.println(dData+ " ");
}
}
class SortedList
{
private Link first;
public SortedList()
{
first=null;
}
public boolean isEmpty()
{
return (first == null);
}
public void insert(long key)
{
Link newLink=new Link(key);
Link prev=null;
Link current=first;
while(current!=null && key > current.dData)
{
prev=current;
current=current.next;
}
if(prev==null)
first=newLink;
else
prev.next=current;
}
public Link remove()
{
Link temp=first;
first=first.next;
return temp;
}
public void displayList()
{
System.out.println("List (first to last-----> ):");
Link current=first;
while(current!=null)
{
current.displayLink();
current=current.next;
}
System.out.println(" ");
}
}
public class SortedLinkedListApp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SortedList thesortedList=new SortedList();
thesortedList.insert(20);
thesortedList.insert(40);
thesortedList.displayList();
thesortedList.insert(30);
thesortedList.insert(50);
thesortedList.displayList();
thesortedList.remove();
thesortedList.displayList();
}
}
/**
* @author Abhinaw.Tripathi
*
*/
class Link
{
public long dData;
public Link next;
public Link(long dd)
{
dData=dd;
}
public void displayLink()
{
System.out.println(dData+ " ");
}
}
class SortedList
{
private Link first;
public SortedList()
{
first=null;
}
public boolean isEmpty()
{
return (first == null);
}
public void insert(long key)
{
Link newLink=new Link(key);
Link prev=null;
Link current=first;
while(current!=null && key > current.dData)
{
prev=current;
current=current.next;
}
if(prev==null)
first=newLink;
else
prev.next=current;
}
public Link remove()
{
Link temp=first;
first=first.next;
return temp;
}
public void displayList()
{
System.out.println("List (first to last-----> ):");
Link current=first;
while(current!=null)
{
current.displayLink();
current=current.next;
}
System.out.println(" ");
}
}
public class SortedLinkedListApp {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
SortedList thesortedList=new SortedList();
thesortedList.insert(20);
thesortedList.insert(40);
thesortedList.displayList();
thesortedList.insert(30);
thesortedList.insert(50);
thesortedList.displayList();
thesortedList.remove();
thesortedList.displayList();
}
}
No comments:
Post a Comment