![]() |
VOOZH | about |
Given a singly linked list containing N nodes, the task is to delete all the even nodes from the list.
Examples:
Input: LL = 1 -> 4 -> 3 -> 18 -> 19
Output: 1 -> 3 -> 19
Input: LL = 5 -> 3 -> 6 -> 8 -> 4 -> 1 -> 2 -> 9
Output: 5 -> 3 -> 1 -> 9
Approach 1:
Below is the implementation of the above idea:
Initial List: 1 -> 4 -> 3 -> 18 -> 19 -> Final List: 1 -> 3 -> 19 ->
Time Complexity: O(N^2)
As the complexity of deleteNode function is O(N) and we need to call it for every even number.
Auxiliary Space: O(1)
As constant extra space is used.
Approach 2:
The idea is to traverse the linked list one by one and get the pointer of nodes having even values. Also keep deleting the nodes having even values using the method used in this post.
We want the time complexity to be O(1) for deleting a given node in order to get O(N) solution for overall approach.
The algorithm for the deleteNode function:
The only thing to keep in mind is that the node to be deleted should not be the last node if we are using the above method to delete the node, but it gives the result in O(1) time so we will use this in our solution.
The algorithm for the deleteEvenNodes function:
Full implementation of above approach:
Initial List: 18 -> 16 -> 15 -> 6 -> 2 -> Final List: 15 ->
Time Complexity: O(N)
As we are visiting every node and deleting odd valued node which is O(1) operation.
Auxiliary Space: O(1)
As constant extra space is used.
Recursive Approach:
Below is the implementation of the above approach:
Output:
Initial List: 18 -> 16 -> 15 -> 6 -> 2 -> NULL
Final List: 15 -> NULL
Time Complexity: O(n), where n is the number of nodes in the linked list.
Space Complexity: O(n), This is because the function creates n recursive function calls on the call stack, one for each node in the linked list.