Reverse a List
excerpt: This covers the basic idea of recursion, identifying the unit of work for each recursive call and doing the work after the recursive calls. tags: unit-of-work two-pointers reduce-input-by-one-unit
Write function that reverses a list in place.
Iterative Implementation
|
|
Recursive Implementation
Given the following input and output:
input {𝑎,𝑏,𝑐,𝑑,𝑒,𝑓,𝑔,h}
output {h,𝑔,𝑓,𝑒,𝑑,𝑐,𝑏,𝑎}
How can we reverse the input to generate the given output?
Idea of Recursion
The first element must be processed by one of the recursive calls, the rest of the elements will be processed by other recursive calls.
𝑎 {𝑏,𝑐,𝑑,𝑒,𝑓,𝑔,h}
{h,𝑔,𝑓,𝑒,𝑑,𝑐,𝑏} 𝑎
The unit of work in this case is processing one element in the input. The work is done after the recursive calls. It gets appended to the array during the return phase of the recursion. This is the key to understanding how the reverse method implements the recursive logic.
Implementation
|
|
We can use the same concept to implement sorting. We can remove the minimum element from the list and insert it at the beginning.
|
|
The unit of work in this sorting method is processing one element. The unit of work is done after the recursive calls. The structure of this program is very similar to the reverse method implementation.
Building Blocks
- Two pointers
- Unit of Work
- Reduce Input by One Unit