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
,head
andnextNode
.newHead
andnextNode
are initialized tonull
.head
starts off pointing to the head of the linked list.
- Iterate (or recursively do) through the following process until
head
isnull
. This means that the end of the list has been reached:
xxxxxxxxxx
26
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 head
let 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