allizwell.jobsdoor360.in

Insertion and Deletion in a Linked List

Data Structures and Algorithms / Linked Lists / Insertion and Deletion

Insertion and Deletion in a Linked List

Insertion and deletion are two fundamental operations performed on linked lists. Insertion adds a new node, while deletion removes an existing node. Unlike arrays, linked lists do not require shifting elements when nodes are inserted or deleted. Instead, we update pointers to maintain the connections between nodes.

1. What Is Insertion in a Linked List?

Insertion is the process of adding a new node to a linked list. A new node can be inserted at different locations:

  • At the beginning of the linked list.
  • At the end of the linked list.
  • At a specific position.
  • After a node containing a particular value.

Example

Suppose we have the following linked list:

10 -> 20 -> 30 -> nullptr

We want to insert 15 between 10 and 20.

10 -> 15 -> 20 -> 30 -> nullptr

We create a new node containing 15 and update the pointers so that 10 points to 15 and 15 points to 20.

2. Structure of a Linked List Node

Before performing insertion and deletion, we need to understand the structure of a singly linked list node.

struct Node {
    int data;
    Node* next;
};
  • data: Stores the value of the node.
  • next: Stores the address of the next node.

The head pointer stores the address of the first node. If the list is empty, head is nullptr.

3. Insertion at the Beginning

Insertion at the beginning means adding a new node before the current first node.

Example

Initially:

Head
 |
 v
10 -> 20 -> 30 -> nullptr

Insert 5 at the beginning:

Head
 |
 v
5 -> 10 -> 20 -> 30 -> nullptr

Algorithm

  1. Create a new node.
  2. Store the given value in the new node.
  3. Make the new node point to the current head.
  4. Update head to the new node.

C++ Code

void insertAtBeginning(Node*& head, int value) {

    Node* newNode = new Node;

    newNode->data = value;

    newNode->next = head;

    head = newNode;
}

Explanation

  • new Node creates a new node dynamically.
  • newNode->data = value stores the value.
  • newNode->next = head connects the new node to the existing list.
  • head = newNode makes the new node the first node.
Important: We pass head by reference using Node*& head because insertion changes the actual head pointer.

4. Insertion at the End

Insertion at the end means adding a new node after the current last node.

Example

Initially:

10 -> 20 -> 30 -> nullptr

Insert 40 at the end:

10 -> 20 -> 30 -> 40 -> nullptr

Algorithm

  1. Create a new node and store the given value.
  2. Set the new node's next pointer to nullptr.
  3. If the list is empty, make the new node the head.
  4. Otherwise, start from head.
  5. Traverse until the last node is reached.
  6. Connect the last node to the new node.

C++ Code

void insertAtEnd(Node*& head, int value) {

    Node* newNode = new Node;

    newNode->data = value;
    newNode->next = nullptr;

    // If the list is empty
    if (head == nullptr) {
        head = newNode;
        return;
    }

    Node* temp = head;

    // Find the last node
    while (temp->next != nullptr) {
        temp = temp->next;
    }

    // Connect the last node
    temp->next = newNode;
}

Dry Run

Consider the list:

10 -> 20 -> 30 -> nullptr
  1. Create a new node containing 40.
  2. Start traversal from node 10.
  3. Move to node 20.
  4. Move to node 30.
  5. Node 30 points to nullptr, so it is the last node.
  6. Set node 30's next pointer to the new node.

10 -> 20 -> 30 -> 40 -> nullptr

5. Insertion at a Specific Position

Sometimes we need to insert a node at a particular position instead of inserting it only at the beginning or end.

In this tutorial, positions are considered 1-based: position 1 means the beginning of the list.

Example

Initially:

10 -> 20 -> 30 -> nullptr

Insert 15 at position 2:

10 -> 15 -> 20 -> 30 -> nullptr

Algorithm

  1. Check whether the position is valid.
  2. If the position is 1, insert at the beginning.
  3. Otherwise, traverse to the node just before the required position.
  4. Create a new node.
  5. Make the new node point to the next node.
  6. Connect the previous node to the new node.

C++ Code

void insertAtPosition(Node*& head, int value, int position) {

    if (position < 1) {
        cout << "Invalid position" << endl;
        return;
    }

    if (position == 1) {
        insertAtBeginning(head, value);
        return;
    }

    Node* temp = head;

    // Move to the node before the position
    for (int i = 1; i < position - 1; i++) {

        if (temp == nullptr) {
            cout << "Invalid position" << endl;
            return;
        }

        temp = temp->next;
    }

    if (temp == nullptr) {
        cout << "Invalid position" << endl;
        return;
    }

    Node* newNode = new Node;

    newNode->data = value;

    newNode->next = temp->next;

    temp->next = newNode;
}
Remember: Always connect the new node to the remaining list before changing the previous node's next pointer. Otherwise, you may lose access to the rest of the linked list.

6. Insertion After a Given Value

We can also insert a node immediately after the first node containing a particular value.

Example

Given list:

10 -> 20 -> 30 -> nullptr

Insert 25 after the value 20:

10 -> 20 -> 25 -> 30 -> nullptr

C++ Code

void insertAfterValue(Node* head, int target, int value) {

    Node* temp = head;

    while (temp != nullptr && temp->data != target) {
        temp = temp->next;
    }

    if (temp == nullptr) {
        cout << "Target value not found" << endl;
        return;
    }

    Node* newNode = new Node;

    newNode->data = value;

    newNode->next = temp->next;

    temp->next = newNode;
}

7. What Is Deletion in a Linked List?

Deletion is the process of removing a node from a linked list. When a node is deleted, its previous node must be connected to its next node.

Deletion can be performed in different ways:

  • Delete the first node.
  • Delete the last node.
  • Delete a node at a specific position.
  • Delete a node containing a particular value.

Example

Initially:

10 -> 20 -> 30 -> nullptr

Delete the node containing 20:

10 -> 30 -> nullptr

The next pointer of node 10 is updated to point directly to node 30. The node containing 20 is then deleted.

8. Deletion from the Beginning

Deletion from the beginning means removing the first node of the linked list.

Example

Before deletion:

Head
 |
 v
10 -> 20 -> 30 -> nullptr

After deleting the first node:

Head
 |
 v
20 -> 30 -> nullptr

Algorithm

  1. Check whether the list is empty.
  2. Store the current head in a temporary pointer.
  3. Move head to the second node.
  4. Delete the old first node.

C++ Code

void deleteFromBeginning(Node*& head) {

    if (head == nullptr) {
        cout << "List is empty" << endl;
        return;
    }

    Node* temp = head;

    head = head->next;

    delete temp;
}
Important: Deleting the first node of a one-node list also makes head nullptr. The same function handles this case correctly.

9. Deletion from the End

Deletion from the end means removing the last node of the linked list.

Example

Before deletion:

10 -> 20 -> 30 -> nullptr

After deleting the last node:

10 -> 20 -> nullptr

Algorithm

  1. Check whether the list is empty.
  2. If only one node exists, delete it and set head to nullptr.
  3. Otherwise, traverse to the second-last node.
  4. Store the last node in a temporary pointer.
  5. Set the second-last node's next pointer to nullptr.
  6. Delete the last node.

C++ Code

void deleteFromEnd(Node*& head) {

    if (head == nullptr) {
        cout << "List is empty" << endl;
        return;
    }

    // Only one node
    if (head->next == nullptr) {
        delete head;
        head = nullptr;
        return;
    }

    Node* temp = head;

    // Find the second-last node
    while (temp->next->next != nullptr) {
        temp = temp->next;
    }

    Node* lastNode = temp->next;

    temp->next = nullptr;

    delete lastNode;
}

10. Deletion at a Specific Position

We can delete a node at a particular position by reaching the node immediately before it and updating the pointers.

Example

Initially:

10 -> 20 -> 30 -> 40 -> nullptr

Delete the node at position 3:

10 -> 20 -> 40 -> nullptr

Algorithm

  1. Check whether the position is valid.
  2. If the position is 1, delete the first node.
  3. Otherwise, traverse to the node before the target position.
  4. Store the node to be deleted.
  5. Connect the previous node to the node after the target.
  6. Delete the target node.

C++ Code

void deleteAtPosition(Node*& head, int position) {

    if (position < 1 || head == nullptr) {
        cout << "Invalid position" << endl;
        return;
    }

    if (position == 1) {
        deleteFromBeginning(head);
        return;
    }

    Node* temp = head;

    // Reach the node before the target
    for (int i = 1; i < position - 1; i++) {

        if (temp == nullptr) {
            cout << "Invalid position" << endl;
            return;
        }

        temp = temp->next;
    }

    if (temp == nullptr || temp->next == nullptr) {
        cout << "Invalid position" << endl;
        return;
    }

    Node* nodeToDelete = temp->next;

    temp->next = nodeToDelete->next;

    delete nodeToDelete;
}

11. Deletion of a Node by Value

Sometimes we know the value of the node that needs to be deleted instead of its position.

Example

Given list:

10 -> 20 -> 30 -> 40 -> nullptr

Delete the node containing 30:

10 -> 20 -> 40 -> nullptr

C++ Code

void deleteByValue(Node*& head, int value) {

    if (head == nullptr) {
        cout << "List is empty" << endl;
        return;
    }

    // If the first node contains the value
    if (head->data == value) {

        Node* temp = head;

        head = head->next;

        delete temp;

        return;
    }

    Node* temp = head;

    // Find the node before the target
    while (temp->next != nullptr &&
           temp->next->data != value) {

        temp = temp->next;
    }

    if (temp->next == nullptr) {
        cout << "Value not found" << endl;
        return;
    }

    Node* nodeToDelete = temp->next;

    temp->next = nodeToDelete->next;

    delete nodeToDelete;
}
Note: This function deletes the first occurrence of the given value. If duplicate values exist, later occurrences remain in the list.

12. Complete C++ Program

The following program demonstrates insertion and deletion operations in a singly linked list.

#include <iostream>
using namespace std;

struct Node {
    int data;
    Node* next;
};

class LinkedList {

private:

    Node* head;

public:

    LinkedList() {
        head = nullptr;
    }

    // Insert at beginning
    void insertAtBeginning(int value) {

        Node* newNode = new Node;

        newNode->data = value;
        newNode->next = head;

        head = newNode;
    }

    // Insert at end
    void insertAtEnd(int value) {

        Node* newNode = new Node;

        newNode->data = value;
        newNode->next = nullptr;

        if (head == nullptr) {
            head = newNode;
            return;
        }

        Node* temp = head;

        while (temp->next != nullptr) {
            temp = temp->next;
        }

        temp->next = newNode;
    }

    // Insert at a position (1-based)
    void insertAtPosition(int value, int position) {

        if (position < 1) {
            cout << "Invalid position" << endl;
            return;
        }

        if (position == 1) {
            insertAtBeginning(value);
            return;
        }

        Node* temp = head;

        for (int i = 1; i < position - 1; i++) {

            if (temp == nullptr) {
                cout << "Invalid position" << endl;
                return;
            }

            temp = temp->next;
        }

        if (temp == nullptr) {
            cout << "Invalid position" << endl;
            return;
        }

        Node* newNode = new Node;

        newNode->data = value;
        newNode->next = temp->next;

        temp->next = newNode;
    }

    // Delete from beginning
    void deleteFromBeginning() {

        if (head == nullptr) {
            cout << "List is empty" << endl;
            return;
        }

        Node* temp = head;

        head = head->next;

        delete temp;
    }

    // Delete from end
    void deleteFromEnd() {

        if (head == nullptr) {
            cout << "List is empty" << endl;
            return;
        }

        if (head->next == nullptr) {
            delete head;
            head = nullptr;
            return;
        }

        Node* temp = head;

        while (temp->next->next != nullptr) {
            temp = temp->next;
        }

        Node* lastNode = temp->next;

        temp->next = nullptr;

        delete lastNode;
    }

    // Delete by value
    void deleteByValue(int value) {

        if (head == nullptr) {
            cout << "List is empty" << endl;
            return;
        }

        if (head->data == value) {

            Node* temp = head;

            head = head->next;

            delete temp;

            return;
        }

        Node* temp = head;

        while (temp->next != nullptr &&
               temp->next->data != value) {

            temp = temp->next;
        }

        if (temp->next == nullptr) {
            cout << "Value not found" << endl;
            return;
        }

        Node* nodeToDelete = temp->next;

        temp->next = nodeToDelete->next;

        delete nodeToDelete;
    }

    // Display list
    void display() {

        if (head == nullptr) {
            cout << "List is empty" << endl;
            return;
        }

        Node* temp = head;

        while (temp != nullptr) {

            cout << temp->data << " ";

            temp = temp->next;
        }

        cout << endl;
    }

    // Destructor
    ~LinkedList() {

        while (head != nullptr) {

            Node* temp = head;

            head = head->next;

            delete temp;
        }
    }
};

int main() {

    LinkedList list;

    list.insertAtEnd(10);
    list.insertAtEnd(20);
    list.insertAtEnd(30);

    cout << "Initial List: ";
    list.display();

    list.insertAtBeginning(5);

    cout << "After inserting at beginning: ";
    list.display();

    list.insertAtEnd(40);

    cout << "After inserting at end: ";
    list.display();

    list.insertAtPosition(25, 4);

    cout << "After inserting at position 4: ";
    list.display();

    list.deleteFromBeginning();

    cout << "After deleting from beginning: ";
    list.display();

    list.deleteFromEnd();

    cout << "After deleting from end: ";
    list.display();

    list.deleteByValue(25);

    cout << "After deleting value 25: ";
    list.display();

    return 0;
}

Output

Initial List: 10 20 30

After inserting at beginning: 5 10 20 30

After inserting at end: 5 10 20 30 40

After inserting at position 4: 5 10 20 25 30 40

After deleting from beginning: 10 20 25 30 40

After deleting from end: 10 20 25 30

After deleting value 25: 10 20 30

13. Time Complexity of Insertion and Deletion

The following table assumes a singly linked list implemented using only a head pointer.

Operation Time Complexity Reason
Insert at beginning O(1) Only a few pointer updates are needed.
Insert at end O(n) Traverse to the last node.
Insert at position O(n) Traverse to the required position.
Delete from beginning O(1) Update head and delete the old node.
Delete from end O(n) Find the second-last node.
Delete at position O(n) Traverse to the node before the target.
Search by value O(n) Check nodes one by one.

Space Complexity

Creating one new node requires O(1) additional space. A linked list containing n nodes requires O(n) total storage space.

14. Array vs Linked List: Insertion and Deletion

Feature Array Linked List
Insertion at beginning O(n) due to shifting O(1)
Insertion at end O(1) amortized for dynamic arrays O(n) with only a head pointer
Deletion at beginning O(n) due to shifting O(1)
Deletion at end O(1) O(n) in a singly linked list
Memory layout Contiguous Non-contiguous
Extra pointer memory Not required per element Required for each node

15. Advantages of Linked List Insertion and Deletion

  • Nodes can be added without shifting existing elements.
  • Deleting a node does not require shifting the remaining nodes.
  • Insertion at the beginning takes O(1) time.
  • Memory is allocated dynamically as needed.
  • Linked lists can grow and shrink during program execution.

16. Common Mistakes

1. Not Updating the Head Pointer

When inserting or deleting the first node, head must be updated. Otherwise, the list may not point to the correct first node.

2. Losing the Remaining List

During insertion, connect the new node to the next node before updating the previous node's pointer.

3. Forgetting to Delete Memory

In C++, nodes created using new should be released using delete when they are removed or when the list is destroyed.

4. Not Handling an Empty List

Always check whether head is nullptr before accessing nodes.

5. Not Handling a Single-Node List

Deleting the only node must set head to nullptr.

6. Using the Wrong Position

Be consistent about whether positions start from 0 or 1. The examples in this topic use 1-based positions.

17. Interview Questions

Q1. What is insertion in a linked list?

Insertion is the process of adding a new node to a linked list by updating the required pointers.

Q2. What is deletion in a linked list?

Deletion is the process of removing a node and reconnecting the remaining nodes.

Q3. What is the time complexity of insertion at the beginning?

O(1), because only a constant number of pointer updates are needed.

Q4. Why does insertion at the end take O(n) time?

When only a head pointer is maintained, we must traverse the list to find the last node.

Q5. How do you delete the first node?

Store the old head, move head to head->next, and delete the old head node.

Q6. What happens when the only node is deleted?

The head pointer becomes nullptr, representing an empty list.

Q7. How can insertion at the end be optimized?

Maintain a tail pointer that directly points to the last node. Insertion at the end can then take O(1) time.

Q8. Why do we use a temporary pointer during deletion?

It stores the address of the node being removed so that its memory can be released safely.

Q9. What is the difference between deleting by position and by value?

Deleting by position removes a node at a specified index, while deleting by value searches for a matching data value.

Q10. Does linked list insertion require shifting elements?

No. It requires changing node pointers instead of shifting existing elements.

18. Practice Problems

  1. Write a program to insert a node at the beginning of a singly linked list.
  2. Write a program to insert a node at the end.
  3. Insert a node at a given 1-based position.
  4. Insert a new node after a given value.
  5. Delete the first node of a linked list.
  6. Delete the last node of a linked list.
  7. Delete a node at a given position.
  8. Delete the first occurrence of a given value.
  9. Count the number of nodes after multiple insertions and deletions.
  10. Implement a menu-driven linked list supporting all insertion and deletion operations.

19. Summary

  • Insertion adds a new node to a linked list.
  • Deletion removes an existing node.
  • Insertion at the beginning takes O(1) time.
  • Deletion from the beginning takes O(1) time.
  • Insertion and deletion at other positions generally require traversal.
  • Pointer updates are essential to maintain the list structure.
  • Always handle empty lists and single-node lists carefully.
  • Use delete to release dynamically allocated nodes.
Key Takeaway: Insertion and deletion in linked lists work by changing pointers rather than shifting elements. Understanding how to connect and disconnect nodes is essential for solving linked list problems efficiently.
Scroll to Top