There are many ways to do the actual reversal, and we'll cover both an iterative and recursive approach, but the general methodology is as follows:
- Begin by creating 3 pointers:
newHead,headandnextNode.newHeadandnextNodeare initialized tonull.headstarts off pointing to the head of the linked list.
- Iterate (or recursively do) through the following process until
headisnull. This means that the end of the list has been reached:
xxxxxxxxxx26
class LinkedListNode { constructor(val, next = null) { this.val = val; this.next = next; }}​l1 = new LinkedListNode(1);l2 = new LinkedListNode(2);l1.next = l2;​// we start at headlet head = l1;let newHead = null;while (head != null) { // store the node to the right to reuse later let nextNode = head.next; // set the current node's next to point backwards head.next = newHead; // store the current node, to be used as the new next later newHead = head; // the previously right-side node is now processed head = nextNode;}​console.log(l2);OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment


