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 ofA
prev
pointer ofB
head
pointer iftarget
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:
-
Finding the Target Node:
- Start from the
head
and traverse the list until you find the node that contains the specified value.
- Start from the
-
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
, updatehead
to point to node B.
-
-
Handling Edge Cases:
- Ensure to check if node A is
NULL
(which means thetarget
node was thehead
) or if node B isNULL
(which means thetarget
node was thetail
).
- Ensure to check if node A is
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.