Insertion of a Node in a Linked List Data Structure
Insertion in Linked List
🚀 Introduction
Insertion is one of the most important operations in a Linked List.
👉 Unlike arrays, insertion in linked list does not require shifting elements, making it more efficient.
🔹 Types of Insertion
- Insert at Beginning
- Insert at End
- Insert at Specific Position
🔹 Structure Reminder
[Data | Next] → [Data | Next] → NULL
🔹 1. Insert at Beginning
💡 Concept
- Create new node
- Point it to current head
- Update head
🧑💻 PHP Code
public function insertAtBeginning($data) {
$newNode = new Node($data);
$newNode->next = $this->head;
$this->head = $newNode;
}🧪 Example
Before:
10 → 20 → 30 → NULL
After inserting 5:
5 → 10 → 20 → 30 → NULL🔹 2. Insert at End
💡 Concept
- Traverse till last node
- Attach new node
🧑💻 PHP Code
public function insertAtEnd($data) {
$newNode = new Node($data); if ($this->head == null) {
$this->head = $newNode;
return;
} $temp = $this->head;
while ($temp->next != null) {
$temp = $temp->next;
} $temp->next = $newNode;
}🧪 Example
Before:
10 → 20 → NULL
After inserting 30:
10 → 20 → 30 → NULL🔹 3. Insert at Specific Position
💡 Concept
- Traverse to position – 1
- Adjust pointers
🧑💻 PHP Code
public function insertAtPosition($data, $position) {
$newNode = new Node($data); if ($position == 1) {
$newNode->next = $this->head;
$this->head = $newNode;
return;
} $temp = $this->head;
for ($i = 1; $i < $position - 1 && $temp != null; $i++) {
$temp = $temp->next;
} if ($temp == null) {
echo "Invalid Position";
return;
} $newNode->next = $temp->next;
$temp->next = $newNode;
}🧪 Example
Before:
10 → 20 → 30 → NULL
Insert 25 at position 3:
After:
10 → 20 → 25 → 30 → NULL⚡ Time Complexity
| Operation | Complexity |
|---|---|
| Insert at Beginning | O(1) |
| Insert at End | O(n) |
| Insert at Position | O(n) |
🎯 Key Points
✅ No shifting like arrays
✅ Efficient insertion
✅ Pointer manipulation is key
🧠 Interview Tips
👉 Always handle edge cases:
- Empty list
- Insert at head
- Invalid position
👉 Common follow-ups:
- Insert in sorted list
- Insert in circular list
🏁 Conclusion
Insertion is a core operation in Linked Lists and is frequently asked in interviews.
👉 Mastering this helps you understand:
- Pointer manipulation
- Linked List flow
- Advanced operations
No comments yet! You be the first to comment.
