π§± 1. What is a Linked List?
A Linked List is a collection of nodes connected like a chain.
Each node contains:
-
valueβ data -
nextβ reference (link) to the next node
[value | next] β [value | next] β [value | null]
π The last node always points to null.
π§ 2. Core Idea (Very Important)
To add a node at the end:
βStart from head β move step by step β find last node β connect new nodeβ
π’ 3. Empty List Case (MOST IMPORTANT START)
If the list is empty:
head = null
Add 5:
We create:
newNode = { value: 5, next: null }
Now:
head β 5 β null
β First node becomes the head
π‘ 4. First Insertion Example
Insert: 5
```text id="a5"
head β null
After push(5):
```text
head β 5 β null
β Head is updated
Insert: 10
Start:
5 β null
Step 1: Create node
10 β null
Step 2: Traverse from head
current = 5
Check:
5.next === null β stop here
Step 3: Attach node
5.next = 10
Result:
5 β 10 β null
π΅ 5. Second Insertion (DETAILED DRY RUN)
Insert: 20
Start:
5 β 10 β null
Step 1: Create node
20 β null
Step 2: Start from head
current = 5
Step 3: Move step-by-step
First move:
5 β 10 β null
β current moves
Now:
current = 10
Step 4: Check next
10.next === null β STOP
π We found last node
Step 5: Attach new node
10.next = 20
Final result:
5 β 10 β 20 β null
π» 6. Final Clean Code
class Node {
constructor(value) {
this.value = value;
this.next = null;
}
}
class LinkedList {
constructor() {
this.head = null;
}
push(value) {
const newNode = new Node(value);
// Case 1: empty list
if (!this.head) {
this.head = newNode;
return;
}
// Case 2: traverse to last node
let current = this.head;
while (current.next) {
current = current.next;
}
// attach new node
current.next = newNode;
}
}
β οΈ 7. VERY IMPORTANT RULES
β Always check this.head (NOT newNode)
β Never do current = newNode β
β Always use current.next = newNode β
β Use while (current.next) for traversal
β±οΈ 8. Complexity
- Without tail: O(n) (you travel whole list)
- With tail pointer: O(1) (instant insert)
π₯ 9. Interview-Level Insight
Linked list insertion at end is not about βadding valueβ
It is about βchanging referencesβ
You are NOT storing memory addresses manuallyβ
JavaScript automatically stores object references.
π§ Final Mental Model
βWalk until null β replace null with new nodeβ
OR
βFind last node β connect next pointerβ





Top comments (0)