Search code examples
javarecursiondata-structureslinked-list

LinkedList not printing the first element in a special case


I am new to recursion concept and while practicing I came across a problem for which I am not able to get a logical reasoning. For the below code snippet, first element of the link is not getting printed (Assume list has more than one elements).

public void foo(ListNode head) {
    foo1(head, head.next);
}

private void foo1(ListNode curr, ListNode nextNode) {
    if (nextNode == null) {
        return;
    }
    curr = nextNode;
    nextNode = curr.next;
    foo1(curr, nextNode);
    System.out.println(curr);
}

Now for example if list has 3 elements as 1 -> 2 -> 3 -> null, only 3 and 2 are getting printed. foo method made a call with head element which is one so shouldn't it print 1 aslo in the output. Please help me understand what I am doing wrong here.


Solution

  •     curr = nextNode;
        ...
        System.out.println(curr);
    

    The problem is you set the curr to its successor before you print it.

    private void foo1(ListNode curr) {
        if (curr == null)
            return;
        System.out.println(curr);
        foo1(curr.next);
    }