Does that all make sense? Be sure to go through the iterative approach a few times.
Here's the recursive way to do it. This can also be tricky, especially on first glance, but realize most of the magic happens when it gets to the end.
xxxxxxxxxx
24
class LinkedListNode {
constructor(val, next = null) {
this.val = val;
this.next = next;
}
}
​
l1 = new LinkedListNode(8);
l2 = new LinkedListNode(4);
l1.next = l2;
​
function reverseList(head) {
if (!head || !head.next) {
return head;
}
​
let rest = reverseList(head.next);
​
head.next.next = head;
delete head.next;
return rest;
}
​
console.log(reverseList(l1));
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment