Friday, April 15, 2011

Link Sort - Sorted Link List


import java.util.Scanner;
public class Node
{
    int info;
    Node next,prev;
    Node left,right;
}

public class LinkSort
{
    Node start=new Node();
    Node end=new Node();
    Node curr=new Node();
    int num;

    LinkSort()
    {
        start=null;
        end=null;
        num=0;
    }
               
    void Add(int val)
    {
        Node t=new Node();
        t.info=val;
        if(num++==0)
            start=t;
        else
        {
            curr=start;
            while((curr.next!=null)&& (val>curr.next.info))
                curr=curr.next;
            t.next=curr.next;
            curr.next=t;           
        }
    }
               
    void Display()
    {
        curr=start;
        System.out.print("Start -> ");
        while(curr!=null)
        {
            System.out.print(curr.info + " -> ");
            curr=curr.next;
        }
        System.out.println("End");
    }
               
    public static void main(String[] args)
    {
        Scanner in = new Scanner(System.in);
        LinkSort l=new LinkSort();
        System.out.println("Enter 5 elements");
        for(int i=0;i<5;i++)
            l.Add(in.nextInt());
        l.Display();
    }
}