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:

102030NULL

After inserting 5:

5102030NULL

🔹 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:

1020NULL

After inserting 30:

102030NULL

🔹 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:

102030NULL

Insert 25 at position 3:

After:

10202530NULL

⚡ 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 *