0

void reverse(Node head) { if(head==null) return;

    reverse(head.next);
    System.out.print(head.data+" ");
}

2 Answers2

3

It prints the content of the linked list from the end.

Consider this simple list : 1 -> 2 -> 3

Now let's 'decompose' the calls:

reverse(1) :
    reverse(2) :
        reverse(3) :
        print(3)
    print(2)
print(1)

The magic happens because println is called after the recursion call ! Try to put it before will print the list in the normal order.

Erwan Daniel
  • 1,319
  • 11
  • 26
1

Essentially, you're reversing the tracing process of a linked list.

void reverse(Node head) {
        if(head==null) //if head points to nothing
             return;
        reverse(head.next); #if head points to something, move one position in reverse, because of the recursion, the function is called again before printing anything
        System.out.print(head.data+" "); #print the data stored in the nodes, reversed
}
Brenden Price
  • 517
  • 2
  • 9