Traverse and update singly linked lists
Quick answer
A singly linked list consists of nodes with a value and a reference to the next node. A head reference locates the first node; null marks the end.
Working examples
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
let head=null;for(const value of [3,2,1])head={value,next:head};const out=[];for(let node=head;node!==null;node=node.next)out.push(node.value);console.log(JSON.stringify(out));Expected console output:
[1,2,3]Each prepend makes the newly inserted node the head.
Run as an independent script in Node.js v22.16.0. ByteMind editor support has not been verified.
let head={value:"A",next:{value:"B",next:{value:"C",next:null}}};let prev=null,current=head;while(current!==null){const next=current.next;current.next=prev;prev=current;current=next;}head=prev;const out=[];for(let n=head;n;n=n.next)out.push(n.value);console.log(out.join(""));Expected console output:
CBASaving the next reference allows every link to be reversed.
How it works and cost model
Prepending a node sets its next to the old head, then replaces head. With a reference to a node, inserting immediately after it changes a constant number of links. Searching by index or value still requires walking the list (O(n) worst-case visits). Reversing an acyclic list changes links while saving the next node before overwriting it; O(n) time and O(1) auxiliary references. Nodes require per-item references and allocation; a linked list is not automatically faster than an array. This lesson assumes acyclic lists.
Common mistakes
Do not overwrite current.next before saving the next node during reversal. Traversal of a cyclic list needs separate detection or a visited set.
Practice
Build a list of three values, prepend a fourth, then reverse it. Check both the empty and singleton cases.
Check Your Understanding
Solidify your learning with the interactive assessment directly below this lesson.
Concept Quiz & Questions
Traverse and update singly linked lists — Knowledge Check
Reason about the algorithm or data structure, its invariants, trade-offs and deterministic outputs.
What is the worst-case number of node visits to find a value in an unsorted singly linked list?
Why store next before reversing current.next?
What is required for constant-link insertion immediately after a singly linked node?
What is the exact console output in the Singly linked list example 1?
let head=null;for(const value of [3,2,1])head={value,next:head};const out=[];for(let node=head;node!==null;node=node.next)out.push(node.value);console.log(JSON.stringify(out));What is the exact console output in the Singly linked list example 2?
let head={value:"A",next:{value:"B",next:{value:"C",next:null}}};let prev=null,current=head;while(current!==null){const next=current.next;current.next=prev;prev=current;current=next;}head=prev;const out=[];for(let n=head;n;n=n.next)out.push(n.value);console.log(out.join(""));