DEV Community

Discussion on: Leetcode - Reverse Linked List(with JavaScript)

Collapse
 
codefinity profile image
Manav Misra

Could you elaborate with an example? I have been struggling with these concepts for a couple of days now. I went about trying to turn a linked list into an array and reversing it and then building it back into a linked list, but that's definitely not ideal, although it does work for most cases.
The example in this article seems a bit contrived with the .next.next - so it may only apply for 'short lists.'
Any other insight is appreciated as to how we can reliably reverse a linked list (in JS) in a 'clean', modern functional way.

Collapse
 
pentacular profile image
pentacular

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))))));
Enter fullscreen mode Exit fullscreen mode

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))))));
Enter fullscreen mode Exit fullscreen mode
Thread Thread
 
codefinity profile image
Manav Misra

I prefer recursion. Tx.