In this article, we will explore how to reverse a singly-linked list using JavaScript. A singly-linked list is a data structure in which each node points to the next node, creating a linear sequence of nodes.
Singly-Linked List Node Definition
In order to work with singly-linked lists, we first need to define a structure for the nodes. In JavaScript, we can use a function constructor to define a ListNode like this:
function ListNode(val, next) {
this.val = val === undefined ? 0 : val;
this.next = next === undefined ? null : next;
}
Here, the ListNode function constructor takes two parameters:
val: The value of the node, which defaults to 0 if not provided.next: A reference to the next node in the list, which defaults tonullif not provided.
Reversing a Singly-Linked List
Now that we have the ListNode definition, let's take a look at the reverseList function, which takes a head node as input and returns the head of the reversed linked list.
/**
* @param {ListNode} head
* @return {ListNode}
*/
var reverseList = function (head) {
let prevNode = null;
let currentNode = head;
let nextNode = null;
while (currentNode) {
nextNode = currentNode.next;
currentNode.next = prevNode;
prevNode = currentNode;
currentNode = nextNode;
}
return prevNode;
};
Here's a step-by-step explanation of the algorithm:
- Initialize three pointers:
prevNode,currentNode, andnextNode. SetprevNodeandnextNodetonull, andcurrentNodetohead. - Iterate through the linked list until
currentNodeisnull. - During each iteration, store the next node in the
nextNodevariable. - Update the
nextpointer ofcurrentNodeto point toprevNode, effectively reversing the link. - Move the
prevNodepointer forward by setting it tocurrentNode. - Move the
currentNodepointer forward by setting it tonextNode. - Once the loop finishes,
prevNodewill be pointing to the new head of the reversed linked list (previously the last node). ReturnprevNode.
By using this reverseList function, we can easily reverse any given singly-linked list in JavaScript.