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.
