Insertion in Linked List (DSA)
π Introduction
Insertion is a fundamental operation in a Linked List, where a new node is added at a specific position.
π Unlike arrays, linked lists do not require shifting elements, making insertion efficient.
πΉ What is a Node?
Each node in a linked list contains:
- Data β Value of the node
- Next Pointer β Address of next node
πΉ Types of Insertion
There are 3 main types:
- Insert at Beginning
- Insert at End
- Insert at a Specific Position
πΉ 1. Insert at Beginning
π‘ Algorithm
- Create a new node
- Set
newNode.next = head - Update
head = newNode
π§Ύ Example
Before:
10 β 20 β 30 β NULL
After inserting 5:
5 β 10 β 20 β 30 β NULL
β‘ Complexity
π O(1) (Fastest insertion)
πΉ 2. Insert at End
π‘ Algorithm
- Create a new node
- Traverse to last node
- Set
last.next = newNode
π§Ύ Example
Before:
10 β 20 β NULL
After inserting 30:
10 β 20 β 30 β NULL
β‘ Complexity
π O(n) (Traversal required)
πΉ 3. Insert at Specific Position
π‘ Algorithm
- Traverse to position – 1
- Set
newNode.next = temp.next - Set
temp.next = newNode
π§Ύ Example
Before:
10 β 20 β 30 β NULL
Insert 25 at position 3:
10 β 20 β 25 β 30 β NULL
β‘ Complexity
π O(n)
βοΈ Pseudocode
function insertAtPosition(head, data, pos):
newNode = createNode(data) if pos == 1:
newNode.next = head
head = newNode
return head temp = head
for i = 1 to pos-1:
temp = temp.next newNode.next = temp.next
temp.next = newNode return head
π― Key Points
β
No shifting of elements (unlike arrays)
β
Efficient insertion using pointers
β
Requires traversal for middle/end insertion
π§ Interview Tips
π Always handle edge cases:
- Empty list
- Position = 1
- Position out of bounds
π Common variations:
- Insert in sorted list
- Insert in circular linked list
- Insert using recursion
β‘ Time Complexity Summary
| Type | Complexity |
|---|---|
| Beginning | O(1) |
| End | O(n) |
| Specific Position | O(n) |
π Conclusion
Insertion is one of the most important operations in Linked Lists.
π Mastering it helps you:
- Understand pointer manipulation
- Solve complex linked list problems
- Perform well in coding interviews
No comments yet! You be the first to comment.
