Clean Markup

Building and Reversing Singly Linked Lists in JavaScript

Building and Reversing Singly Linked Lists in JavaScript

While JavaScript developers work primarily with contiguous dynamic arrays, understanding node-and-pointer data structures like Linked Lists is essential for mastering memory layouts, queues, LRU caches, and algorithmic reasoning.

In a Singly Linked List, each element is a standalone node containing a value and a pointer (next) to the following node, enabling (O(1)) insertions and deletions at the head without memory shifting.

Example

class ListNode {
  constructor(val, next = null) {
    this.val = val;
    this.next = next;
  }
}

Implementation

Reversing a singly linked list in-place using an iterative three-pointer technique:

function reverseList(head) {
  let prev = null;
  let current = head;

  while (current !== null) {
    const nextTemp = current.next; // Store next node
    current.next = prev;           // Reverse pointer direction
    prev = current;                // Advance prev pointer
    current = nextTemp;            // Advance current pointer
  }

  return prev; // New head of reversed list
}

// Example usage:
const head = new ListNode(1, new ListNode(2, new ListNode(3)));
const reversedHead = reverseList(head);
console.log(reversedHead.val); // 3

Complexity Analysis

Main Point: In-place linked list reversal requires tracking prev, current, and next pointers to redirect node references without auxiliary memory allocation.

Credits

Photo by Luca Bravo on Unsplash

← Home