Insertion in Linked List (DSA)

Insertion in Linked List

πŸš€ 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:

  1. Insert at Beginning
  2. Insert at End
  3. Insert at a Specific Position

πŸ”Ή 1. Insert at Beginning

πŸ’‘ Algorithm

  1. Create a new node
  2. Set newNode.next = head
  3. 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

  1. Create a new node
  2. Traverse to last node
  3. 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

  1. Traverse to position – 1
  2. Set newNode.next = temp.next
  3. 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

TypeComplexity
BeginningO(1)
EndO(n)
Specific PositionO(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.

Leave a Reply

Your email address will not be published. Required fields are marked *