1

I have this assingment where I have to implement a single linked list class in java, but, it's required to be implemented entirely with recursive functions, even the constructor.

The constructor given in the project provided by the teacher receives an array of n generic elements with the 3-dot notation (T ... elements) and after scratching my head a little bit (I've never done a recursive constructor) I've come up with something that obviously doesn't work:

public SingleLinkedListImpl(T ... elements) {
    if(elements.length<=1){
        header = new Node<T>(elements[0]);
    } else {
        addLast(elements[0]);
        elements=Arrays.copyOfRange(elements, 1, elements.length-1);
        this(elements);
    }
}

The IDE im currently working with, says this cant be done because if I refer to the constructor with this, inside the constructor itself it MUST be the first statement in the function.

How do I proceed with this issue?

BTW: I cant use anything from the Collections API

2
  • You could try overloading the constructor. Commented Apr 21, 2019 at 20:52
  • I've tryed implementing and using a SimpleLinkedListImpl(T element) in the recursive calls but the error persist. Commented Apr 21, 2019 at 21:28

1 Answer 1

3

“Recursive constructor” doesn’t equate to calling this(), but rather calling new SingleLinkedListImpl().

Also, this is the head, rather than has a head.

Assuming your class has next and value fields, in pseudo code:

  • if the array is empty, throw an IllegalArgumentException
  • set value to the first element of the array
  • if there is more than 1 element in the array, set the value of next to new SingleLinkedListImpl(<elements 1 to n>)

To call it:

SingleLinkedListImpl<Integer> head = new SingleLinkedListImpl<>(3, 1, 4, 1, 5); // for example
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.