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.
// 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
}
// 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);
next must end up as null.head is null) and a single-node list must both return safely. No throws.null. You don't need to detect loops.Node class — the test harness builds plain { val, next } objects.