Example 1: Reversing a linked list
Order in a singly linked list
is determined by a node's next property. The next pointer can refer to another node or it can point to null.
Reversing a linked list
means reassigning all the next properties on every node. So we are going from this:

To this:

There are many ways to reverse a linked list
however the way I will demonstrate a simple way using 3 pointers. The idea is to use the three pointers: next
, current
, and prev
.
In the reverse(Node head)
method, the current
is the main pointer running down the list. The next
pointer leads it and the prev
pointer trails it. In each iteration, the current
pointer is reversed and then advance all three to get the next node.
xxxxxxxxxx
45
print(reversed);
function reverseList(head) {
let prev = null;
let current = head;
​
while (current != null) {
const next = current.next;
​
current.next = prev;
​
prev = current;
current = next;
}
​
return prev;
}
​
function print(head) {
let finalStr = "";
let current = head;
while (current != null) {
finalStr += current.val + " -> ";
current = current.next;
}
finalStr += "null";
console.log(finalStr);
}
​
class Node {
constructor(val, next) {
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment