I have an assignment in my java class that i need to recursively print out a linked list in reverse. I have looked online and found numerous examples of recursive methods that do this but take a node in as a parameter, and to my understanding i need to take in a linked list because i need to print the entire list out. Below is what code i have written, and it works in the sense that it prints out the list, recursively, but it is still in the same order that i created the list. After it prints out the list it throws a no such element exception as well. my main problem/question is wrapping my head around how best to print this recursively.
public void printRecurse2(LinkedList<String> list2)
{
if(list2 == null)
return;
System.out.println(list2.pop());
printRecurse2(list2);
}
Your
listwill never benull, this is why the recursion doesn’t stop in time. You need to check whether the list is not empty, instead of for null, e.g.This avoids the exception. To print in reverse, you need to start from the other end of the list: