This post will reverse the singly linked list using recursion in C, C++, Java, and Python.

For example,

Input:  1 —> 2 —> 3 —> 4 —> 5 —> null
 
Output: 5 —> 4 —> 3 —> 2 —> 1 —> null

Practice this problem

We have already discussed an iterative solution to reverse the linked list in the previous post. In this post, we will cover the recursive implementation of it.

Following is the simple recursive implementation that works by fixing .next pointers of the list’s nodes and finally the head pointer. Probably the hardest part is accepting the concept that the reverse(&rest, head) does reverse the rest. Then, there’s a trick to getting the one front node at the end of the list. We recommend making a drawing to see how the trick works.

C


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> NULL

C++


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> nullptr

Java


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> null

Python


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> None

We can also solve this problem by passing only reference to the head pointer to the function, as demonstrated below:

C


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> NULL

C++


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> nullptr

Java


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> null

Python


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> None

We can simplify the above code by passing previous node information to the function. Following is a simple recursive implementation of it in C, C++, Java, and Python:

C


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> NULL

C++


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> nullptr

Java


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> null

Python


Download  Run Code

Output:

6 —> 5 —> 4 —> 3 —> 2 —> 1 —> None

The time complexity of the above recursive solutions is O(n), where n is the length of the linked list. The solution is probably not appropriate for production code since it uses stack space proportionate to the lists’ lengths. Still, it provides good learning on how recursion works.

 
Source: http://cslibrary.stanford.edu/105/LinkedListProblems.pdf