Bird
Raised Fist0
DSA Typescriptprogramming~15 mins

Insert at Beginning Head Insert in DSA Typescript - Deep Dive

Choose your learning style10 modes available
Overview - Insert at Beginning Head Insert
What is it?
Insert at Beginning Head Insert is a way to add a new item at the very start of a linked list. A linked list is a chain of items where each item points to the next one. By inserting at the beginning, the new item becomes the first in the chain, pushing the others back. This operation changes the head, or the start, of the list.
Why it matters
Without the ability to insert at the beginning, adding new items to a linked list would be slower or more complex. This method lets us quickly add items to the front, which is useful in many programs like undo features, stacks, or real-time data feeds. Without it, managing lists would be less efficient and harder to control.
Where it fits
Before learning this, you should understand what a linked list is and how nodes connect. After this, you can learn about inserting at the end, deleting nodes, or traversing the list. This step is an early building block in mastering linked list operations.
Mental Model
Core Idea
Inserting at the beginning means making a new node point to the current first node, then updating the head to this new node.
Think of it like...
Imagine a line of people holding hands. To add a new person at the front, the new person grabs the hand of the first person, and now the new person is at the front of the line.
Head -> [New Node] -> [Old First Node] -> [Next Node] -> null
Build-Up - 6 Steps
1
FoundationUnderstanding Linked List Nodes
🤔
Concept: Learn what a node is and how it stores data and a link to the next node.
A node is like a box with two parts: one holds the data (like a number or word), and the other holds a reference (or pointer) to the next node in the list. If there is no next node, this reference is null.
Result
You can picture a chain of boxes, each pointing to the next, forming a linked list.
Understanding nodes is key because linked lists are built from these simple connected units.
2
FoundationWhat is the Head of a Linked List?
🤔
Concept: The head is the first node in the linked list and entry point to access all nodes.
The head is a variable that points to the first node. If the list is empty, head is null. To access or change the list, you start from the head and follow the links.
Result
Knowing the head lets you find and manipulate the entire list.
The head is the gateway to the list; changing it changes the whole list's start.
3
IntermediateInserting a Node at the Beginning
🤔Before reading on: do you think inserting at the beginning requires changing the head pointer or just the new node's pointer? Commit to your answer.
Concept: To insert at the beginning, create a new node, point it to the current head, then update head to this new node.
Steps: 1. Create a new node with the data. 2. Set new node's next to current head. 3. Update head to new node. This makes the new node the first in the list.
Result
The list now starts with the new node, followed by the old nodes.
Knowing that the head must be updated prevents losing the list's start and keeps the chain intact.
4
IntermediateHandling Empty List Insertion
🤔Before reading on: do you think inserting at the beginning in an empty list is different from a non-empty list? Commit to your answer.
Concept: When the list is empty (head is null), inserting at the beginning means the new node becomes the only node and head points to it.
If head is null: - Create new node. - Set new node's next to null. - Set head to new node. This initializes the list with one node.
Result
The list now has one node, and head points to it.
Handling empty lists correctly avoids errors and ensures the list starts properly.
5
AdvancedTypeScript Implementation of Head Insert
🤔Before reading on: do you think the insert function should return the new head or modify it directly? Commit to your answer.
Concept: Implement the insert at beginning operation in TypeScript with proper types and class structure.
class Node { data: T; next: Node | null; constructor(data: T) { this.data = data; this.next = null; } } class LinkedList { head: Node | null = null; insertAtBeginning(data: T): void { const newNode = new Node(data); newNode.next = this.head; this.head = newNode; } printList(): void { let current = this.head; let result = ''; while (current) { result += current.data + ' -> '; current = current.next; } result += 'null'; console.log(result); } } // Example usage: const list = new LinkedList(); list.insertAtBeginning(10); list.insertAtBeginning(20); list.insertAtBeginning(30); list.printList();
Result
Output: 30 -> 20 -> 10 -> null
Seeing the full code connects theory to practice and shows how head insert works in real code.
6
ExpertWhy Head Insert is O(1) Time Complexity
🤔Before reading on: do you think inserting at the beginning takes time proportional to list size or constant time? Commit to your answer.
Concept: Inserting at the beginning always takes the same small number of steps, regardless of list size.
The operation only changes two pointers: the new node's next and the head pointer. It does not need to look through the list. This means the time it takes does not grow with the list length.
Result
Head insert is very fast and efficient, even for very long lists.
Understanding constant time operations helps choose the right data structure for performance.
Under the Hood
When inserting at the beginning, memory is allocated for a new node. This node's 'next' pointer is set to the current head's memory address. Then, the head pointer is updated to point to this new node's memory address. This changes the entry point to the list without moving or copying existing nodes.
Why designed this way?
Linked lists were designed to allow efficient insertions and deletions without shifting elements like arrays. Updating the head pointer is a simple, fast way to add nodes at the front. Alternatives like arrays require moving many elements, which is slower.
Head Pointer
   ↓
+---------+      +---------+      +---------+      +-------+
| NewNode | ---> | OldNode | ---> | NextNode| ---> | null  |
+---------+      +---------+      +---------+      +-------
Myth Busters - 3 Common Misconceptions
Quick: Does inserting at the beginning require traversing the entire list? Commit to yes or no.
Common Belief:Many think you must walk through the whole list to insert at the beginning.
Tap to reveal reality
Reality:You only need to update the new node's next to the current head and then update head to the new node; no traversal is needed.
Why it matters:Believing traversal is needed leads to inefficient code and misunderstanding of linked list performance.
Quick: After inserting at the beginning, does the old head node get lost? Commit to yes or no.
Common Belief:Some believe the old head node is replaced or lost after insertion.
Tap to reveal reality
Reality:The old head node remains linked after the new node; it is now the second node in the list.
Why it matters:Misunderstanding this can cause bugs where data is accidentally discarded.
Quick: Is inserting at the beginning slower for longer lists? Commit to yes or no.
Common Belief:People often think insertion speed depends on list length.
Tap to reveal reality
Reality:Insertion at the beginning is always constant time, independent of list size.
Why it matters:This misconception can lead to wrong data structure choices and performance issues.
Expert Zone
1
In some languages, careless head insertions without proper memory management can cause memory leaks or dangling pointers.
2
When using immutable data structures, head insertion creates a new list version sharing tail nodes, enabling efficient persistent lists.
3
In concurrent environments, head insertion requires synchronization to avoid race conditions on the head pointer.
When NOT to use
Head insertion is not suitable when order matters and new elements must be added at the end. In such cases, use tail insertion or doubly linked lists for efficient end insertions.
Production Patterns
Head insertion is commonly used to implement stacks (LIFO), undo functionality, and real-time event logs where newest data must be accessed first.
Connections
Stack Data Structure
Head insertion in linked lists is the core operation behind push in stacks.
Understanding head insert clarifies how stacks efficiently add and remove items from the top.
Immutable Persistent Data Structures
Head insertion creates new versions of lists sharing tails without copying all nodes.
Knowing this helps understand how functional programming languages manage data efficiently.
Human Queue Management
Inserting at the beginning is like letting someone cut to the front of a line, changing the order instantly.
This real-world behavior helps grasp how linked list head insertions reorder elements quickly.
Common Pitfalls
#1Forgetting to update the head pointer after insertion.
Wrong approach:function insertAtBeginning(data) { const newNode = new Node(data); newNode.next = head; // head not updated }
Correct approach:function insertAtBeginning(data) { const newNode = new Node(data); newNode.next = head; head = newNode; }
Root cause:Not realizing that head must point to the new node to keep the list connected.
#2Setting new node's next pointer to null instead of current head.
Wrong approach:function insertAtBeginning(data) { const newNode = new Node(data); newNode.next = null; // wrong head = newNode; }
Correct approach:function insertAtBeginning(data) { const newNode = new Node(data); newNode.next = head; // correct head = newNode; }
Root cause:Misunderstanding that new node must link to the existing list to avoid losing nodes.
#3Assuming head insert changes the order of existing nodes.
Wrong approach:// Incorrectly rearranging nodes after insertion function insertAtBeginning(data) { const newNode = new Node(data); newNode.next = head.next; // skips old head head = newNode; }
Correct approach:function insertAtBeginning(data) { const newNode = new Node(data); newNode.next = head; // points to old head head = newNode; }
Root cause:Confusing the role of pointers and the head node in maintaining list order.
Key Takeaways
Inserting at the beginning of a linked list means creating a new node that points to the current head and then updating the head to this new node.
This operation is very fast and always takes constant time, no matter how long the list is.
Properly updating the head pointer is crucial to keep the list connected and avoid losing data.
Handling empty lists correctly ensures the list starts properly without errors.
Understanding head insertion is foundational for many data structures like stacks and persistent lists.

Practice

(1/5)
1. What does the "Insert at Beginning" operation do in a singly linked list?
easy
A. Adds a new node at the start of the list
B. Adds a new node at the end of the list
C. Deletes the first node of the list
D. Deletes the last node of the list

Solution

  1. Step 1: Understand the operation

    Inserting at the beginning means adding a new node before the current first node.
  2. Step 2: Effect on the list

    The new node becomes the head, pushing the old head to second position.
  3. Final Answer:

    Adds a new node at the start of the list -> Option A
  4. Quick Check:

    Insert at beginning = Add new head [OK]
Hint: Insert at beginning means new head node [OK]
Common Mistakes:
  • Confusing insert at beginning with insert at end
  • Thinking it deletes nodes
  • Assuming it changes the tail node
2. Which of the following is the correct TypeScript syntax to insert a new node at the beginning of a singly linked list?
easy
A. newNode = head; head.next = newNode;
B. head = newNode.next; newNode = head;
C. head.next = newNode; newNode = head;
D. newNode.next = head; head = newNode;

Solution

  1. Step 1: Link new node to current head

    Set newNode.next to point to current head node.
  2. Step 2: Update head to new node

    Assign head to newNode so it becomes the first node.
  3. Final Answer:

    newNode.next = head; head = newNode; -> Option D
  4. Quick Check:

    Link new node to head, then update head [OK]
Hint: Set newNode.next to head, then head = newNode [OK]
Common Mistakes:
  • Assigning head before linking newNode.next
  • Swapping assignments order
  • Using head.next instead of newNode.next
3. What will be the linked list after executing the following TypeScript code?
class Node {
  value: number;
  next: Node | null = null;
  constructor(value: number) { this.value = value; }
}

let head: Node | null = new Node(10);
let newNode = new Node(5);
newNode.next = head;
head = newNode;
medium
A. 10 -> null
B. 10 -> 5 -> null
C. 5 -> 10 -> null
D. 5 -> null

Solution

  1. Step 1: Initial list setup

    head points to node with value 10, next is null.
  2. Step 2: Insert newNode at beginning

    newNode (5) points to head (10), then head updated to newNode.
  3. Final Answer:

    5 -> 10 -> null -> Option C
  4. Quick Check:

    New node 5 becomes head, points to 10 [OK]
Hint: New node points to old head, then becomes new head [OK]
Common Mistakes:
  • Confusing order of nodes after insertion
  • Forgetting to update head
  • Assuming newNode.next is null
4. Identify the error in this TypeScript code that tries to insert a node at the beginning of a linked list:
class Node {
  value: number;
  next: Node | null = null;
  constructor(value: number) { this.value = value; }
}

let head: Node | null = null;
let newNode = new Node(7);
head.next = newNode;
head = newNode;
medium
A. head is null, so head.next causes an error
B. newNode is not linked to head
C. head should be assigned before newNode.next
D. Missing constructor call for newNode

Solution

  1. Step 1: Check initial head value

    head is null, so accessing head.next is invalid and causes runtime error.
  2. Step 2: Correct insertion approach

    Assign newNode.next = head (which is null), then head = newNode.
  3. Final Answer:

    head is null, so head.next causes an error -> Option A
  4. Quick Check:

    Cannot access property on null head [OK]
Hint: Check if head is null before accessing head.next [OK]
Common Mistakes:
  • Trying to access next on null head
  • Not linking newNode.next to head
  • Assigning head after using head.next
5. Given a singly linked list with nodes 20 -> 30 -> 40 -> null, what will be the list after inserting 10 at the beginning using head insert method?
hard
A. 20 -> 30 -> 40 -> 10 -> null
B. 10 -> 20 -> 30 -> 40 -> null
C. 30 -> 40 -> 10 -> 20 -> null
D. 10 -> 30 -> 40 -> 20 -> null

Solution

  1. Step 1: Understand initial list

    List is 20 -> 30 -> 40 -> null, head points to 20.
  2. Step 2: Insert 10 at beginning

    Create new node 10, set newNode.next = head (20), then head = newNode.
  3. Final Answer:

    10 -> 20 -> 30 -> 40 -> null -> Option B
  4. Quick Check:

    New node 10 becomes head, old list follows [OK]
Hint: New node points to old head, becomes new head [OK]
Common Mistakes:
  • Appending new node at end instead of beginning
  • Mixing node order after insertion
  • Not updating head pointer
Recommended

Ready to prove it?

Pass the test and this pattern moves unknown strong while earning +1 Grip toward your certificate.

10 questions~5 mineasy hard