Recursion on a linkedlist

Collapse
X
 
  • Time
  • Show
Clear All
new posts
  • chetah
    New Member
    • Sep 2008
    • 10

    Recursion on a linkedlist

    Code:
    import java.io.*;
    import java.util.*;
    
    class LinkedList<T extends Comparable <T>>
    {
    	private Node head;
    	private Node last;
    	private T data;
    
    	public LinkedList()
    	{
    		head = null;
    	}
    
    	public boolean isEmpty()
    	{
    		return (head==null);
    	}
    
    
    	public void addToHead (T val)
    	{
    		Node n = new Node (val);
    		n.next = head;
    		head = n;
    	}
    
    
    	private class Node
    	{
            public T data;
            public Node next;
    
            Node (T val)
            {
            	data = val;
            	next = null;
            }
    	}
    
    
    
    
    public void insertOrdered(T val){
    	insertOrdered(head, val);
    }
    
    public Node insertOrdered(Node head, T val)
      {
         Comparable <T> temp = (Comparable<T>)val;
    
        if (head == null || temp.compareTo(head.data)== 0)
          head = new Node(val);
        else
          head.next = insertOrdered(head.next, val);
    
        return head;
      }
    
    
        public String toString()
        {
        	String str ="";
        	Node curr = head;
        	while(curr!=null)
        	{
        		str = str + curr.data + " ";
        		curr = curr.next;
        	}
        	return str + "\n";
        }
    
    
    
    
    }//end linkedList
    
    class Link2
    {
    	public static void main(String[] arg)
    	{
    		LinkedList<Integer> s1 = new LinkedList<Integer>();
    
    		s1.addToHead(23);
    		s1.addToHead(78);
    		s1.addToHead(100);
    		s1.insertOrdered(6);
    		s1.insertOrdered(67);
    		s1.insertOrdered(1);
    		s1.insertOrdered(7);
    
    
    
    		System.out.println(s1.toString());
    	}
    }
    I am trying to get the insertOrdered method to sort numbers as they are entered but is does not work. What might be the problem with this method? Help in rectifying!
    Thank You!!
Working...