What is actually happening in the code here

50 views Asked by At

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

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

There are 2 answers

0
Erwan Daniel On

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.

0
Brenden Price On

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
}