Using a stack abstraction
const push = (item, list) => ({ item, next: list }); const pop = (list) => [list.next, list.item]; const reverse = (list) => { let reversed = null; while (list !== null) { [list, item] = pop(list); reversed = push(reversed, item); } return reversed; } console.log(JSON.stringify(reverse(push(3, push(2, push(1, null))))));
Or, if you prefer recursion
const push = (item, list) => ({ item, next: list }); const reverse = (list, reversed = null) => list === null ? reversed : reverse(list.next, push(list.item, reversed)); console.log(JSON.stringify(reverse(push(3, push(2, push(1, null))))));
I prefer recursion. Tx.
Are you sure you want to hide this comment? It will become hidden in your post, but will still be visible via the comment's permalink.
Hide child comments as well
Confirm
For further actions, you may consider blocking this person and/or reporting abuse
We're a place where coders share, stay up-to-date and grow their careers.
Using a stack abstraction
Or, if you prefer recursion
I prefer recursion. Tx.