I have encountered an issue with my current implementation where it only works properly for lists with a length of two or less. When the list is longer, I lose the nodes in the middle. How can I modify the return object after the recursive call to handle lists of any length while also preserving the nodes in the middle?
In this code snippet, Type List refers to the head of the list and ConsCell represents a node in the list
type List = null | ConsCell;
type ConsCell = {
readonly first: number;
readonly rest: List;
}
function reverse(list: List): List {
}
Your task is to implement the reverse function so that it returns the reversed version of the input list.
Here are some examples:
input: null (empty list) output: null
input: { first: 1, rest: null } output: { first: 1, rest: null }
input: { first: 1, rest: { first: 2, rest: { first: 3, rest: null } } } output: { first: 3, rest: { first: 2, rest: { first: 1, rest: null } } }
Remember, you should create a new list as the output without modifying the input list
Current solution:
function reverse(list: List): List {
if(!list) {
return null;
}
else if(list.rest == null) {
return {
first: list.first,
rest: list.rest
};
}
else {
let oldRest: List = reverse(list.rest);
return {
first: oldRest.first,
rest: {
first: list.first,
rest: null
}
}
}
}