Linked List ReversalLoading saved progress…

Linked List Reversal

A singly linked list is a chain of nodes where each node holds a val and a next pointer to the following node. Reversing one is a classic interview warm-up — it shows up in real code any time you need to walk a chain backward (undo stacks, history traversal, parsing). See MDN on data structures for the general idea, though linked lists aren't built into JavaScript.

Implement linkedListReversal(head). Given the head of a singly linked list, reverse the direction of every next pointer and return the new head (which is the old tail). Do it in place — don't allocate new nodes.

Signature

// Each node has the shape:
// { val: any, next: Node | null }

function linkedListReversal(head) {
  // returns the new head of the reversed list, or null if head is null
}

Examples

// Input:  1 -> 2 -> 3 -> 4 -> null
// Output: 4 -> 3 -> 2 -> 1 -> null
linkedListReversal(buildList([1, 2, 3, 4]));
// Input:  42 -> null         (single node)
// Output: 42 -> null         (same node, same value)
linkedListReversal(buildList([42]));

// Input:  null               (empty list)
// Output: null
linkedListReversal(null);

Notes

  • In place — reuse the existing nodes. Don't build a new list and copy values across.
  • Return the new head — that's the node that was previously the tail. The old head becomes the new tail and its next must end up as null.
  • Edge cases — an empty list (head is null) and a single-node list must both return safely. No throws.
  • No cycles — assume the input list is well-formed and ends in null. You don't need to detect loops.
  • Don't worry about doubly linked lists, dummy heads, or a Node class — the test harness builds plain { val, next } objects.
Loading editor…