Singly Linked List
Example
let prev = null, node = head;
while (node) {
node.next = prev;
prev = node;
node = node.next;
}let prev = null, node = head;
while (node) {
const next = node.next;
node.next = prev;
prev = node;
node = next;
}Saving next first keeps a handle on the rest of the list; otherwise the loop stops after the first node.
Common mistakes
- Losing the rest of the list by overwriting
nexttoo early. - Forgetting to update
headwhen deleting the first node.
Key points
- When reversing or relinking, the next pointer is saved before it is overwritten.
- Appends at the end keep a tail pointer; otherwise each append walks the list in O(n).
- Traversal loops check
node !== nullbefore readingnode.next.
Interview questions
What is the time complexity of a singly linked list?
Insert or delete at the head is O(1). Access by index and search are O(n).
Singly vs doubly linked list: what is the difference?
A doubly linked list also stores a previous pointer, so it can walk backward and delete a known node in O(1), at the cost of more memory.
Does JavaScript have a built-in linked list?
No, JavaScript has no linked list type. Arrays cover most needs; write a small node class when you need one.
