Write a function to reverse a singly linked list
Reversing a singly linked list is a classic computer science problem that tests your understanding of data structures and algorithms. In JavaScript, where we don’t have built-in linked list structures, we’ll need to implement them first. This post will walk you through creating a function to reverse a singly linked list.
First, let’s define a Node class and a LinkedList class to represent our linked list:
class Node {
constructor(data) {
this.data = data;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
append(data) {
const newNode = new Node(data);
if (!this.head) {
this.head = newNode;
return;
}let current = this.head;
while (current.next) {
= current.next;
current
}.next = newNode;
current
} }
Now, let’s tackle the core problem: reversing the linked list. There are many approaches, but an iterative approach is often preferred for its efficiency. We’ll use three pointers: previous
, current
, and next
.
function reverseLinkedList(list) {
let previous = null;
let current = list.head;
let next = null;
while (current) {
= current.next; // Store the next node
next .next = previous; // Reverse the current node's pointer
current= current; // Move previous pointer forward
previous = next; // Move current pointer forward
current
}
.head = previous; // Update the head of the list
list }
Let’s break down how this works:
Initialization: We start with
previous
asnull
,current
as the head of the list, andnext
asnull
.Iteration: The
while
loop continues as long as there are nodes left to process (current
is notnull
).Pointer Manipulation: Inside the loop,
next
stores the next node in the sequence. Then,current.next
is set toprevious
, effectively reversing the direction of the pointer.previous
is updated tocurrent
, andcurrent
moves tonext
.Head Update: Finally,
list.head
is set toprevious
, which is now the tail of the original list, but the new head of the reversed list.
Here’s an example of how to use this function:
const myList = new LinkedList();
.append(1);
myList.append(2);
myList.append(3);
myList.append(4);
myList.append(5);
myList
reverseLinkedList(myList);
let currentNode = myList.head;
let reversedList = "";
while (currentNode) {
+= currentNode.data + " ";
reversedList = currentNode.next;
currentNode
}
console.log(reversedList); // Output: 5 4 3 2 1
This code creates a linked list, reverses it using reverseLinkedList
, and then prints the reversed list to the console. This demonstrates a clear and efficient way to reverse a singly linked list in JavaScript. Remember that this solution operates in-place, modifying the original list directly, rather than creating a new reversed list.