Insertion of a Node in a Linked List Data Structure

Insertion of a Node in a Linked List

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

  1. Insert at Beginning
  2. Insert at End
  3. 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

OperationComplexity
Insert at BeginningO(1)
Insert at EndO(n)
Insert at PositionO(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.

Leave a Reply

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