Problem Link - Delete from front
Problem Statement:
Complete the function deleteNode to delete an element from the front of the linked list. In the next
lesson, we will learn how to delete an element from any other position.
Approach:
The key idea of this solution is to delete the node that matches a given value and update the head if the node being deleted is the first node.
Here’s how the approach works:
-
Check if the node to delete is the head: If the node to be deleted is the head (i.e., the node at the start of the list), we need to update the head to the
next
node in the list. -
Update the head pointer: The head is updated to point to the
next
node in the list. -
Delete the target node: After updating the
head
, the old head (which contains the value to be deleted) is removed from memory usingdelete
.
Time Complexity:
- O(1) because the function only checks the head node and updates the
head
pointer.
Space Complexity:
- O(1) since no additional data structures are used.