Even with such a short piece of code there is a lot to say.
Firstly, your example code is an example, designed to test just one piece of skill. A real list should never expose the fact that the implementation relies on a ListNode
. In fact, your method is private, indicating that the detail is not public. The real printReverse method should have no argument, and should be public, because it should start with the head node of the list, and use that to start the recursive reverse print.
Also, that would be the right place to handle the nulls....
Recursive methods often (normally?) come in pairs, a setup method, and the actual recursive method. Your pair would look like:
public void printReverse() {
if (head == null) {
System.out.println("null");
} else {
printReverseRecursive(head);
}
}
private void printReverseRecursive(ListNode node) {
if (node == null) {
return;
}
printReverseRecursive(node.next);
System.out.print(node.val + " ");
}
Note, that while we are there, you have one of those wtf moments in your variable names. the name l1
is a really, really bad name. l
is very easy to confuse with 1
, and should never be used as a simple 1-letter variable name, and then, to make it worse, you put them together? Huh.