Input: 7 → 20 → 9 → 10 → 20 → 14 → 15 → 20, X = 10, Y = 20
Output: 7 → 20 → 9 → 10 → 14 → 15
Input: LL: 10 → 20, X = 10, Y = 20
Output: LL: 10
Approach: The given problem can be solved by traversing the given Linked List and delete all the nodes with value Y occurring after the node with value X. Follow the steps below to solve the problem:
- Initialize two list nodes K and prev, to store the current head of the given Linked List and the previous node of the current head of the Linked List.
- Traverse the given Linked List until K becomes NULL and perform the following steps:
- Iterate the node K until a node with value X is found and simultaneously update the node prev as the previous of node K.
- Store the node K in another variable, say temp, and traverse the Linked List until the node with value Y has occurred and simultaneously update the node prev as the previous of node K.
- If the value of temp is NULL, then break out of the loop. Otherwise, update the next pointer of prev to the next pointer of temp and update temp to the next pointer of the node prev.
- After completing the above steps, print the modified Linked List.
Below is the implementation of the above approach:
7 20 9 10 10 15
Time Complexity: O(N)
Auxiliary Space: O(1)