Search code examples
javalinked-listsequences

Java Linked List Sequence insertFirst method inserts object twice


I am trying to implement a Linked List Sequence in Java however my method for inserting an object at the start of the sequence inserts the object twice and I don't understand why.

If anyone can help it would be really appreciated.

The current output of my test program is

30 30

but I want it to be 30

Thanks in advance

Below is the code for the sequence and the method for insertFirst

public class Sequence implements SequenceInterface{

private Node listHead; 
private Node listTail; 

protected class Node{

      protected Object datum; 
      protected Node next; 

      public Node(Object o, Node n) { 
           datum = o; 
           next = n; 
      }

}


//Constructor 
public Sequence(){ 
   listHead = null; 
   listTail = null;
}


public void insertFirst(Object o) {

    if(listHead == null){

         listHead = new Node(o, listTail); 
         listTail = listHead; 

    }else{
        Node oldLH = listHead;
        listHead = new Node(o, oldLH);
    }       
}
}

Here is my test program

public class SequenceTest {
/**
 * @param args
 * @throws Exception 
 */
public static void main(String[] args) throws Exception {
    Sequence s = new Sequence();    
    s.insertFirst(new Integer(30));

    for(int i=0; i<2; i++){
        System.out.println(s.element(i));
    }
}
}

Solution

  • It looks like it is only added once, but is being printed twice.

    If you unroll the loop:

    for(int i=0; i<2; i++){
        System.out.println(s.element(i));
    }
    

    you essentially get:

    System.out.println(s.element(0));
    System.out.println(s.element(1));
    

    so if this is unexpected behaviour, what we really need to look at to diagnose it is the element() method.

    What do you want to happen when s.element(2) is called and 's' only contains one element? Should it throw an index out of range exception? Should it wrap or crop to within range when it is indexed past the lists range (presumably the current behaviour)?