“Reverse Linked List” Javascript solution Cheat Sheet

Fadi Tillman
2 min readJun 26, 2021

The “Reverse Linked List” is in the easy category and is a good start for understanding more challenging algorithms using a linked list as a data structure. I will focus on explaining a solution that works and not on the O time and space complexity.

Challenge: “Given the head of a singly linked list, reverse the list, and return the reversed list.”LeetCode

Note:

// Singly linked list data structure// Given head “Object”// Reverse the list// Return reversed list

Example:

input: head =[5,6,7,8,9,10]  next
|
5 -> 6 -> 7 -> 8 -> 9 -> 10 -> null
| |
Head
Tail
return: [10,9,8,7,6,5] next
|
10 -> 9 -> 8 -> 7 -> 6 -> 5 -> null
| |
Head Tail

Explanation:

Create variables to keep track of reassigned values and iterate until we reach the end of the linked list.

1.Create variables to keep track

let currentNode = head;
let previousNode = null;
let nextNode = null;

2.Iterate until the end of the linked list when the head is equal to null

while (currentNode){
}

3.Reassign nodes values

nextNode = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;

4.Return reversed list link

return previousNode;

Solution :

var reverseList = function(head) {

let currentNode = head;
let previousNode = null; let nextNode = null;

while(currentNode ){

nextNode = currentNode.next;
currentNode.next = previousNode;
previousNode = currentNode;
currentNode = nextNode;
}
return previousNode;
};

--

--