participate


Generics - Sorting a linked list, throw duplicates and stack overflow errors
<<   Back to Forum  |   Give us Feedback
This topic has 2 replies on 1 page.
AdRock
Posts:4
Registered: 1/26/08
Sorting a linked list, throw duplicates and stack overflow errors   
Jan 27, 2008 3:32 PM

 
I am having a few problems with a sorted linked list I have written

It all compiles fine but when I run it, i come into problems

The first noticeable problem is that it is not getting sorted. When I print the first element, it prints the first element added (which is 6 not 1), not the beginning of the set and it'e the same for the last (which is 1 not 6).

Also how do i get it to throw duplicate entries? In my example I have added 1 twice and I only want it to add it once.

Another problem is when i try and use the iterator, it throws null pointer exceptions.

The last problem is when i try and print the subSet, tailSet and headSet. I get a stack overflow error.

Any ideas how i can get this working?

import java.util.*;
 
public class OrderedLinkedList<E> extends AbstractSet<E> implements SortedSet<E> {
    
    private Node<E> head;
    private Node<E> current;
    private int numberContents;
 
    public OrderedLinkedList() {
    	
    	head = new Node<E>(null);
    	numberContents = 0;
    }
 
    public boolean add(E cargo){
        Node<E> nextNode = new Node<E>(cargo);
        if(numberContents == 0){
            head = nextNode;  
        }
        else{
            Node<E> current = head;
            for(int i=1; i< numberContents; i++){
                current=current.getNext();
            }
            current.setNext(nextNode);
        }
        numberContents++;
        return true;
    }
 
    public int size() {
        return numberContents;
    }
	
    public boolean isEmpty() {
        return head == null;
    }
	
    public E first() {
        if (isEmpty()) {
            throw new NoSuchElementException();
        }
        current = head;
        return head.getContents();
    }
 
    public E last() {
        if(isEmpty()){
            throw new NoSuchElementException();
        }
        for(int i=1; i < numberContents; i++){
           current = current.getNext(); 
        }
        
        return current.getContents(); 
    }
          	
    public SortedSet<E> tailSet(E fromElement) {
        
        if (isEmpty()) {
            throw new NullPointerException();
        }
        OrderedLinkedList oll = new OrderedLinkedList();
        
        SortedSet<E> tail = oll.tailSet(fromElement+"\0");
        return tail;
    }
  	
    public SortedSet<E> headSet(E toElement) {
        
        if (isEmpty()) {
            throw new NullPointerException();
        }
        OrderedLinkedList oll = new OrderedLinkedList();
        
        SortedSet<E> head = oll.headSet(toElement+"\0");
        return head;
    }
  	
    public SortedSet<E> subSet(E fromElement, E toElement) {
        
        //if (isEmpty()) {
        //    throw new NullPointerException();
        //}  
        OrderedLinkedList oll = new OrderedLinkedList();
        	      
        SortedSet<E> sub = oll.subSet(fromElement, toElement+"\0");
        return sub;
    }  	
  		
    public Iterator<E> iterator() {
    	
        return new Iterator<E>() {
        	
            E valueReturned;
            private int counter = 0;
            
            public boolean hasNext() {
                if (counter >= numberContents){
                    return false;
                }
                else {
                    counter++;
                    return true;
                }
            }
            
            public E next() {
                valueReturned = current.getContents();
                current = current.getNext();
                return valueReturned;
            }
            
            public void remove() {
                throw new UnsupportedOperationException();
            }     
        };
    } 
    	
    public Comparator<E> comparator(){
    
    	return new Comparator<E>() {
  	
            public int compare(E obj1, E obj2) {
                Node<E> node1 = (Node) obj1;
    			Node<E> node2 = (Node) obj2;
                
     			return node1.compareTo(node2.getContents());            
            }	
 
  			public boolean equals(Object obj) {            	         	
        		if (!(obj instanceof OrderedLinkedList)) {
                    return false;
        		}
 
        		Node<E> newNode = (Node) obj;
        		return current.getContents().equals(newNode.getContents());
        	}
    	};
    }
    
    public static void main(String Args[]){
       OrderedLinkedList linkedList = new OrderedLinkedList();
       
       linkedList.add(new Node("6"));
       linkedList.add(new Node("2"));
       linkedList.add(new Node("4"));
       linkedList.add(new Node("3"));
       linkedList.add(new Node("1"));
       linkedList.add(new Node("1"));
       
       int size = linkedList.size();
       System.out.println("Number of elements in list " + size);
       System.out.println("The first element is " + linkedList.first());
       System.out.println("The last element is " + linkedList.last());
       
       System.out.println("The tailSet is " + linkedList.tailSet("4"));
       System.out.println("The headSet is " + linkedList.headSet("4"));
       System.out.println("The subSet is " + linkedList.subSet("4", "1"));
       
       Iterator itr = linkedList.iterator();
 
       while(itr.hasNext()){
            Object element = itr.next();
            System.out.println(element + "\n");
       }     
   }      
}


and this is my Node class

import java.util.*;
 
public class Node<E> implements Comparable<E>{
    Node<E> next;             // Refers to next item in the list.
    Node<E> previous;         // Refers to the previous item.       ***
    E cargo;               // The item for this Node.
 
	// Constructor: 
    public Node(E cargo) {
        this.cargo = cargo;        // Store the item.
        next = null;  // Set next and previous to null.      ***
        previous = null;
    }
 
  	// Set the pointer to the next Node:
    public void setNext(Node<E> next) {
        this.next = next;        // Store reference to the next item.
    }
  
    // Additional method to set the pointer to the previous Node:  ***
    public void setPrevious(Node<E> previous) {                                                               
        this.previous = previous; // Store reference to the previous item. 
    }
 
    // Get the next item in the list:
    public Node<E> getNext() {
        return next;
    }
 
    // Additional method to get the previous item in the list:         ***
    public Node<E> getPrevious() {
        return previous;
    }
 
    // Get the object for this item:
    public E getContents() {
        return cargo;
    }
 
    // Return class name & object:
    public String toString() {
        return ""+ cargo;
    }
 
    public int compareTo(E obj) {
    	Node<E> newNode = (Node<E>) obj;
    	int nodeComp = ((Comparable<E>)cargo).compareTo(newNode.getContents());
 
    	return nodeComp;
    }
}
 
spoon_
Posts:506
Registered: 12/14/06
Re: Sorting a linked list, throw duplicates and stack overflow errors   
Jan 27, 2008 6:36 PM (reply 1 of 2)  (In reply to original post )

 
wow there are so many problems with this; here are some for starters:

in tailSet(), headSet(), and subSet(), you have code like the following; i have no idea in the world what you are trying to do here
OrderedLinkedList oll = new OrderedLinkedList();
SortedSet<E> tail = oll.tailSet(fromElement+"\0");

you create a new string from the string representation of "fromElement", appended with the "\0" character (???)
and then you recursively call the method on a new instance of OrderedLinkedList (which throws NullPointerException), with input being that bizarre string you created above

in add(), it always add things to the end. is this what you want? how is it "ordered"?

Node<E> should implement Comparable<Node<E>>; you cannot cast E into Node<E>

in the Comparator returned by comparator(), you cannot cast E into Node<E>

* the "current" variable should be inside Iterator; there can be multiple iterators at different places
 
AdRock
Posts:4
Registered: 1/26/08
Re: Sorting a linked list, throw duplicates and stack overflow errors   
Jan 28, 2008 1:00 AM (reply 2 of 2)  (In reply to #1 )

 
spoon_ wrote: in tailSet(), headSet(), and subSet(), you have code like the following; i have no idea in the world what you are trying to do here
OrderedLinkedList oll = new OrderedLinkedList();
SortedSet<E> tail = oll.tailSet(fromElement+"\0");

you create a new string from the string representation of "fromElement", appended with the "\0" character (???)
and then you recursively call the method on a new instance of OrderedLinkedList (which throws NullPointerException), with input being that bizarre string you created above

I looked everywhere online for an example of how to do these emthods but found nothing apart from one site which did this
SortedSet set = s.headSet(toElement+"\0");

This is all it showed so i don't know what to put here.

in add(), it always add things to the end. is this what you want? how is it "ordered"?

When I add a node I would like to order them ascending so in my example it should start at 1 being the first node and 6 being the last but not accepting duplicates

Node<E> should implement Comparable<Node<E>>; you cannot cast E into Node<E>

is this right?
public class Node<E> implements Comparable<Node <E>>{
    Node<E> next;
    //etc

I don't know what to do but am presuming this is what you mean

in the Comparator returned by comparator(), you cannot cast E into Node<E>

What do i cast into Node?

* the "current" variable should be inside Iterator; there can be multiple iterators at different places

I thought it was but if you can help with this too i would be very grateful. I am really stuck with this and it has taken so long to get this far
 
This topic has 2 replies on 1 page.
Back to Forum
 
Read the Developer Forums Code of Conduct

Click to email this message Email this Topic

Edit this Topic
  
 
 
Forums Statistics

About Sun forums
  • Oracle Forums is a large collection of user generated discussions. It is here to help you ask questions, find answers, and participate in discussions.

    Check out our guide on Getting started with Oracle Forums for a full walkthrough of how to best leverage the benefits of this community.

Powered by Jive Forums