DEV Community

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

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.