Try to search your question here, if you can't find : Ask Any Question Now ?

Printing linked-list recursively

HomeCategory: stackoverflowPrinting linked-list recursively
willson asked 2 weeks ago

I am trying to print a linked list of “Honor roll students” recursively. i have 6 students added to the linked list but when i call the method to return the linked-list of honor roll students recursively it is only returning the first student in the honor roll and not the 2 others that should be there as well. i managed to print the honor roll students Iterative but the recursion keeps giving me the first student.

 //Recursive 

 public ArrayList<Student> honorsStudentsRec (Node first)
 {
    Node current = first;

    ArrayList<Student> honorRollArray = new ArrayList<Student>();
    if(current.next == null)
        return null;
    else if(current.data.isHonors())
    { 
        honorsStudentsRec(current.next);
        honorRollArray.add(current.data);
        return honorRollArray;
    }
    else
    {
        return honorsStudentsRec(current.next);
    }

   //Iterative

    public ArrayList<Student> honorsStudents()
    {
        Node current = list;
        ArrayList<Student> honorRollArray = new ArrayList<Student>();

        while(current != null)
        {
            if(current.data.isHonors())
                honorRollArray.add(current.data);
            current = current.next;
        }

        return honorRollArray;
    }

Im expecting the recursive method to work the same way as the iterative method just using recursion.

1 Answers
Best Answer
Arben answered 2 weeks ago
Your Answer

7 + 6 =

Popular Tags

WP Facebook Auto Publish Powered By : XYZScripts.com