Understand the structure of singly linked lists, implement core operations, and compare their performance with doubly linked lists and arrays.
A singly linked list is a sequence of nodes connected in one direction. Each node stores a value and a next reference to the following node.
The list keeps a head reference to its first node and a tail reference to its last node. The tail's next points to null, which marks the end of the list.
Think of the structure like a scavenger hunt:
null), signaling that the hunt is over.Key Property: Unidirectional
From any node, you can follow next one step forward. To find a node by value, start at the head and follow links until you find a match or reach the end. The stored tail gives direct access to the last node.
| Component | Description |
|---|---|
| Node | Stores a value and a next reference. |
| Head | References the first node. |
| Tail | References the last node. Its next is null. |
| Length | Tracks the number of nodes for fast boundary checks. |
In this chain, each node holds a fruit name in val and a reference in next. Following the first node's next takes you to the node holding banana.
To implement a singly linked list in code, we define two classes:
Node: Holds the data and the reference to the next node.SinglyLinkedList: Manages the chain, tracking head, tail, and length.class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class SinglyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
}Tracking tail and length gives us two immediate performance advantages:
Start with the four operations at the ends. For each one, predict what happens to head, tail, and length when the list contains just one node. Then use get to see how edits by index differ from edits at a known node. The complete class near the end is a reference you can run.
push)The push method appends a new node to the end of the list.
!this.head), point both head and tail to the new node.tail.next to point to the new node, and update tail to be the new node.length by 1.push(val) {
const newNode = new Node(val);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
return this;
}Time Complexity: O(1) — Direct pointer update through the tail pointer.
unshift)The unshift method prepends a new node to the start of the list, making it the new head.
head and tail to the new node.next pointer to reference the current head.head to reference the new node.length by 1.unshift(val) {
const newNode = new Node(val);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
this.length++;
return this;
}Time Complexity: O(1) — Unlike arrays where prepending requires shifting every element to the right (O(n)), adding to the head of a linked list is instant.
shift)The shift method removes the node at the head of the list and returns it.
null.head node in a temporary variable.head to head.next.length by 1.length reaches 0, set tail to null.next pointer and return it.shift() {
if (!this.head) return null;
const removedNode = this.head;
this.head = this.head.next;
this.length--;
if (this.length === 0) {
this.tail = null;
}
removedNode.next = null;
return removedNode;
}Time Complexity: O(1) — Constant time. In an array, removing from index 0 takes O(n) time because all remaining elements must shift left.
pop)The pop method removes the node at the tail of the list and returns it.
Why is Pop O(n) in a Singly Linked List?
Even though we have a tail pointer, removing the tail requires pointing the second-to-last node to null and making it the new tail. Because singly linked lists only point forward, we must traverse the entire list from the head to locate that second-to-last node.
null.head: current and newTail.current.next exists: advance newTail to current, and current to current.next.current is the tail. In a list of two or more nodes, newTail is its predecessor. In a one-node list, the loop skips and both references still identify that node.tail to newTail and disconnect its next pointer (tail.next = null).length by 1.length reaches 0, reset both head and tail to null.current.pop() {
if (!this.head) return null;
let current = this.head;
let newTail = current;
while (current.next) {
newTail = current;
current = current.next;
}
this.tail = newTail;
this.tail.next = null;
this.length--;
if (this.length === 0) {
this.head = null;
this.tail = null;
}
return current;
}Time Complexity: O(n) — Must traverse to the second-to-last node.
get)The get method retrieves the node at a given 0-based index.
Unlike arrays, where index lookups are instant (O(1)) using memory offsets, a singly linked list must count forward from head step by step.
index < 0 or index >= this.length, return null.current at this.head.index times, moving current = current.next.current.get(index) {
if (index < 0 || index >= this.length) return null;
let current = this.head;
for (let i = 0; i < index; i++) {
current = current.next;
}
return current;
}Time Complexity: O(n) — Requires sequential traversal from the head.
set)The set method modifies the value stored in the node at a specific index.
get(index) to find the target node.true.false.set(index, val) {
const foundNode = this.get(index);
if (foundNode) {
foundNode.val = val;
return true;
}
return false;
}Time Complexity: O(n) — Inherited from the traversal in get.
insert)The insert method inserts a new node at any valid index (0 through length).
The straight link from 10 to 20 is the original pointer. The curved arrows show the proposed links through 15. After the update, 10 has exactly one next reference, pointing to 15.
index < 0 or index > this.length, return false.index === 0, let unshift(val) complete the insertion and return success.index === this.length, let push(val) complete the insertion and return success.get(index - 1).next to prev.next.prev.next to point to the new node.length and return true.insert(index, val) {
if (index < 0 || index > this.length) return false;
if (index === 0) return Boolean(this.unshift(val));
if (index === this.length) return Boolean(this.push(val));
const prev = this.get(index - 1);
const newNode = new Node(val);
newNode.next = prev.next;
prev.next = newNode;
this.length++;
return true;
}Time Complexity: O(n) — Finding the position takes O(n) traversal, but the pointer rewiring itself is instant (O(1)).
remove)The remove method deletes the node at a given index and returns it.
index < 0 or index >= this.length, return null.index === 0, return the node removed by shift().index === this.length - 1, return the node removed by pop().prev = this.get(index - 1).removedNode = prev.next.prev.next = removedNode.next.removedNode.next = null.length and return the removed node.remove(index) {
if (index < 0 || index >= this.length) return null;
if (index === 0) return this.shift();
if (index === this.length - 1) return this.pop();
const prev = this.get(index - 1);
const removedNode = prev.next;
prev.next = removedNode.next;
removedNode.next = null;
this.length--;
return removedNode;
}Time Complexity: O(n) — Locating the node takes O(n), while unlinking is O(1).
reverse)Reversing a singly linked list in-place is one of the classic data structure algorithms. It inverts the direction of all pointer links so that the head becomes the tail, the tail becomes the head, and all intermediate links point backward.
To flip links without losing references to the rest of the list, we maintain three pointers as we traverse:
prev: Starts at null.current: Starts at this.head.next: Temporarily preserves the upcoming node (current.next).current, then swap the list's head and tail references.current is not null:
next = current.next (saves remaining chain).current.next = prev.prev forward: prev = current.current forward: current = next.reverse() {
let current = this.head;
this.head = this.tail;
this.tail = current;
let prev = null;
let next = null;
while (current) {
next = current.next; // 1. Save next node
current.next = prev; // 2. Reverse pointer direction
prev = current; // 3. Step prev forward
current = next; // 4. Step current forward
}
return this;
}Time Complexity: O(n) — Single pass through all n nodes.
Space Complexity: O(1) — Done entirely in-place with three temporary pointer variables.
print)A helper method to print the elements of the list sequentially for debugging and inspection:
print() {
const values = [];
let current = this.head;
while (current) {
values.push(current.val);
current = current.next;
}
console.log(values.join(" -> ") + " -> null");
}The example builds the chain 5 → 10 → 15 → 20 → 30. Predict which node will be the tail after reverse(), then check by running the class.
class Node {
constructor(val) {
this.val = val;
this.next = null;
}
}
class SinglyLinkedList {
constructor() {
this.head = null;
this.tail = null;
this.length = 0;
}
push(val) {
const newNode = new Node(val);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
this.tail.next = newNode;
this.tail = newNode;
}
this.length++;
return this;
}
unshift(val) {
const newNode = new Node(val);
if (!this.head) {
this.head = newNode;
this.tail = newNode;
} else {
newNode.next = this.head;
this.head = newNode;
}
this.length++;
return this;
}
shift() {
if (!this.head) return null;
const removedNode = this.head;
this.head = this.head.next;
this.length--;
if (this.length === 0) {
this.tail = null;
}
removedNode.next = null;
return removedNode;
}
pop() {
if (!this.head) return null;
let current = this.head;
let newTail = current;
while (current.next) {
newTail = current;
current = current.next;
}
this.tail = newTail;
this.tail.next = null;
this.length--;
if (this.length === 0) {
this.head = null;
this.tail = null;
}
return current;
}
get(index) {
if (index < 0 || index >= this.length) return null;
let current = this.head;
for (let i = 0; i < index; i++) {
current = current.next;
}
return current;
}
set(index, val) {
const foundNode = this.get(index);
if (foundNode) {
foundNode.val = val;
return true;
}
return false;
}
insert(index, val) {
if (index < 0 || index > this.length) return false;
if (index === 0) return Boolean(this.unshift(val));
if (index === this.length) return Boolean(this.push(val));
const prev = this.get(index - 1);
const newNode = new Node(val);
newNode.next = prev.next;
prev.next = newNode;
this.length++;
return true;
}
remove(index) {
if (index < 0 || index >= this.length) return null;
if (index === 0) return this.shift();
if (index === this.length - 1) return this.pop();
const prev = this.get(index - 1);
const removedNode = prev.next;
prev.next = removedNode.next;
removedNode.next = null;
this.length--;
return removedNode;
}
reverse() {
let current = this.head;
this.head = this.tail;
this.tail = current;
let prev = null;
let next = null;
while (current) {
next = current.next;
current.next = prev;
prev = current;
current = next;
}
return this;
}
print() {
const values = [];
let current = this.head;
while (current) {
values.push(current.val);
current = current.next;
}
console.log(values.join(" -> ") + " -> null");
}
}
// Example Usage
const list = new SinglyLinkedList();
list.push(10).push(20).push(30);
list.print(); // 10 -> 20 -> 30 -> null
list.unshift(5);
list.print(); // 5 -> 10 -> 20 -> 30 -> null
list.insert(2, 15);
list.print(); // 5 -> 10 -> 15 -> 20 -> 30 -> null
list.reverse();
list.print(); // 30 -> 20 -> 15 -> 10 -> 5 -> null| Operation | Time Complexity |
|---|---|
| Push at tail | O(1) |
| Pop from tail | O(n) |
| Unshift at head | O(1) |
| Shift from head | O(1) |
| Get or set by index | O(n) |
| Insert or remove by index | O(n) |
| Search | O(n) |
| Reverse | O(n) |
Understanding the performance trade-offs between linked lists and arrays allows you to choose the right data structure for your specific use case.
| Operation | Singly Linked List | Array / Dynamic Array | Architectural Explanation |
|---|---|---|---|
| Access (by index) | O(n) | O(1) | Arrays calculate physical memory addresses via arithmetic offset; linked lists must traverse sequentially from head. |
| Search (by value) | O(n) | O(n) | Both must inspect elements one by one in unsorted collections. |
Insertion at Head (unshift) | O(1) | O(n) | Linked list rewires a single pointer; arrays must shift every subsequent element one position to the right. |
Insertion at Tail (push) | O(1) | O(1) amortized | The list updates its tail directly. A dynamic array occasionally copies O(n) items to grow. |
| Insertion in Middle | O(n) | O(n) | Linked list spends O(n) traversing to the position; array spends O(n) shifting elements. |
Deletion at Head (shift) | O(1) | O(n) | Linked list advances head; array must shift every remaining item left. |
Deletion at Tail (pop) | O(n) | O(1) | Singly linked list must traverse from head to find the second-to-last node; array decrements its size counter. |
| Deletion in Middle | O(n) | O(n) | Linked list requires O(n) traversal; array requires O(n) shifting. |
| Memory Allocation | Node by node | Contiguous slots in the array model | Array slots sit side by side. A slot can hold a reference to an object stored elsewhere. |
| Memory Overhead | A link per node | Spare capacity | Each node stores next. A dynamic array may reserve slots for future appends. |
unshift and shift to add and remove from the same end in O(1) time.push at the tail and shift at the head; both operations take O(1) time.data[450]), arrays provide instant O(1) access whereas linked lists require slow O(n) traversal.next reference.next reference.head to tail; there is no direct backward traversal.push)Step-by-Step Logic2. Adding to the Beginning (unshift)Step-by-Step Logic3. Removing from the Beginning (shift)Step-by-Step Logic4. Removing from the End (pop)Step-by-Step Logic5. Accessing by Index (get)Step-by-Step Logic6. Updating by Index (set)Step-by-Step Logic7. Inserting at Any Position (insert)Step-by-Step Logic8. Removing from Any Position (remove)Step-by-Step Logic9. Reversing the List (reverse)The Three-Pointer AlgorithmStep-by-Step Loop10. Displaying the List (print)Complete ImplementationPerformance SummarySingly Linked List vs. ArraysApplications and When to Use a Singly Linked ListOptimal Use CasesWhen to AvoidKey Takeaways