mercredi 29 novembre 2017

Recursion - insert value at the front and at the end of list

I am having some trouble with this method. It is supposed to insert a value at the given index.

    public Element insertElementAt(int value, int index) {

    if (index == 0 || this.next == null) { 
        Element newElement = new Element();
        System.out.println("you are in the loop");
        newElement.setNext(this);
        System.out.println("you are still in the loop");
        return this;
    }
else if (this.next !=null) {
        index--;
        this.next = this.next.insertElementAt(value, index);
        return this;
    }
    if (this.next== null){
        return this; 
    }
    return this;
}

The idea is, that the method should be able to insert a value at the front, in the middle and at the end of my Element. I am still pretty new to recursion, but have managed to come this far - also why i have added System.out.println.
I am pretty sure, that I only need to change/add/delete a line or two, but I cannot figure out where. Also I am sure it is in the if-statement.

Test cases just in case:

  @Test
public void testInsertElementAt_Front() {
    Element el = createElements(0, 1, 2);
    Element result = el.insertElementAt(11, 0);
    System.out.println(result.showValues());
    assertEquals(11, result.getValue());
    assertEquals(0, result.getNext().getValue());
}

@Test
public void testInsertElementAt_Middle() {
    Element el = createElements(0, 1, 2);
    Element result = el.insertElementAt(11, 1);
    System.out.println(result.showValues());
    assertEquals(0, result.getValue());
    assertEquals(11, result.getNext().getValue());
}

@Test
public void testInsertElementAt_End() {
    Element el = createElements(0, 1);
    System.out.println(el.showValues()); 
    Element result = el.insertElementAt(11, 2);
    System.out.println(result.showValues()); 
    assertEquals(0, result.getValue());
    assertEquals(1, result.getNext().getValue());
    assertEquals(11, result.getNext().getNext().getValue());
    assertNull(result.getNext().getNext().getNext());
}

And the output:

For testInsertElementAt_Front():
junit.framework.AssertionFailedError: expected:<11> but was:<0>

For testInsertElementAt_Middle():
junit.framework.AssertionFailedError: expected:<11> but was:<1>

For testInsertElementAt_End: java.lang.NullPointerException

Any help would be appreciated

Aucun commentaire:

Enregistrer un commentaire