HeftyDolphin
HeftyDolphin

Reputation: 53

How to recursively display the elements of a list?

I have got this so for which will do it successfully but it will also print the empty list message but I'm not too sure why? I'm still learning about recursion so apologises if I have missed something simple.

public void recursiveDisplayElements(MyList<Integer> m) {

    // -----------------------------
    // I. SCENARIO IDENTIFICATION
    // -----------------------------
    int scenario = 0;

    if (m.length() == 0) {

        scenario = 1;
    } else {

        scenario = 2;
    }
    // -----------------------------
    // II. SCENARIO IMPLEMENTATION
    // -----------------------------

    switch (scenario) {

    case 1:

        System.out.println("MyList is empty!");
        break;

    case 2:

        int e0 = m.getElement(0);
        m.removeElement(0);
        System.out.print(e0);
        recursiveDisplayElements(m);
        m.addElement(0, e0);

    }

}

Upvotes: 1

Views: 237

Answers (2)

Justin
Justin

Reputation: 1356

Seeing as you can only use one method, perhaps you can implement it without removing from the list and passing in an index as well. public void recursiveDisplayElements(MyList<Integer> m, int index) to kick things off you would call with your list and 0 as index. If index==0 && m.size() == 0, you can display System.out.println("MyList is empty!"); otherwise you could print m.getElement(index) and then call recursiveDisplayElements(m, index++); until index == m.size()-1)

Upvotes: 1

Exayls
Exayls

Reputation: 26

in this recursive function, each time the list is not empty, the function will remove one element from it and print it. It will continue to do so until the list is totally emptied and go in the case 1 where it will write that the list is empty.

In a recursive function the case number 1 is the stop case wich will always be executed at the end.

Sorry if my explication isn't clear.

Upvotes: 1

Related Questions