LINK02P06 - Editorial

Problem Link - Deletion - Doubly Linked List

Problem Statement:

Let’s suppose you need to delete the node target between node A and node B, the pointers we need to update are:

  • next pointer of A
  • prev pointer of B
  • head pointer if target is the head

Complete the function delete(int val) where val denotes the value of the node to be deleted.

Approach:

The key idea of this function is to find the target node with the specified value and then adjust the pointers of its neighboring nodes (if they exist) to remove it from the list.

Here’s how the approach works:

  1. Finding the Target Node:

    • Start from the head and traverse the list until you find the node that contains the specified value.
  2. Updating Pointers:

    • Once the target node is found, identify its previous node (A) and next node (B).

    • Update the next pointer of node A to point to node B.

    • Update the prev pointer of node B to point to node A.

    • If the target node is the head, update head to point to node B.

  3. Handling Edge Cases:

    • Ensure to check if node A is NULL (which means the target node was the head) or if node B is NULL (which means the target node was the tail).

This approach efficiently removes the node while ensuring the list remains connected.

Time Complexity:

  • O(n) in the worst case, where n is the number of nodes in the list, as we may need to traverse the entire list to find the target node.

Space Complexity:

  • O(1) since we are only using a constant amount of space for pointers and do not require additional data structures.