HiveBrain v1.2.0
Get Started
← Back to all entries
patternjavaMinor

Printing a singly linked list in reverse order

Submitted by: @import:stackexchange-codereview··
0
Viewed 0 times
orderreversesinglyprintinglistlinked

Problem

I am preparing for interview and I want to write the function in the way that the interviewers will expect me to write.

private static void printReverse(ListNode l1){
        if(l1 != null){
            printReverse(l1.next);
            System.out.print(l1.val + " ");
        }
    }


However, this function does not do anything if l1 is null. Should I take care of this case? If yes, how?

Solution

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.

Code Snippets

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 + " ");
}

Context

StackExchange Code Review Q#63658, answer score: 8

Revisions (0)

No revisions yet.