无法从LinkedList递归检索128个以上的元素

时间:2018-10-05 16:44:27

标签: java recursion linked-list

我可以成功地递归检索127个元素。

我尝试了非递归方式来成功添加和检索500个元素。

但是当我尝试递归检索这500个元素时,测试失败:     Java.langAssertionError:     预期:是<128>     但是:为空

public class Node<T> {
    private T element;
    private Node<T> next;

    public Node(T element, Node<T> next) {
        this.element = element;
        this.next = next;
    }
    public T getElementRecurisvely(T element) {

        if (this.element == element) return this.element;

        return (next==null)? null: next.getElementRecurisvely(element);     
    }
...
}

public class LinkedList<T>{
    private Node<T> head;
    private Node<T> tail;

    public T getRecurisvely(T element) {    
        if (element == null) return null;
        if (head==null) return null;        
        Node<T> currNode=head;      
        return (T) currNode.getElementRecurisvely(element);
        }
...
}

public class LinkedListTests {
    @Test
    public void should__retrieve_elements() {
        LinkedList<Integer> sut = new LinkedList<>();

        for(Integer i=0; i<500; i++) {
            sut.add(i);
        }
        //if I change i<500 to i<128, the test will pass
        for(Integer i=0; i<500; i++) {
            //this assertion will pass
            assertThat(sut.get(i), is(i));
            //fails at the 128 element
            assertThat(sut.getRecurisvely(i),is(i));
        }
    }
...
}        

0 个答案:

没有答案