Given a Linked List and a key K. The task is to write a program to delete all the nodes from the list that are lesser than the key K.
Input :12->15->9->11->5->6 K = 9 Output : 12 -> 15 -> 9 -> 11 Input : 13->4->16->9->22->45->5->16->6 K = 10 Output : 13 -> 16 -> 22 -> 45 -> 16
Approach: The approach is similar to deleting all nodes from the list which are greater than the given key.
There are two possible cases:
- Head node holds a value less than K: First check for all occurrences at head node which are lesser than ‘K’, delete them and change the head node appropriately.
- Some intermediate node holds value less than k: Start traversing from head and check if current node’s value is less than K. If yes then delete that node and move forward in the list.
Below is the implementation of the above approach:
Initial List: 12 15 9 11 5 6 Final List: 12 15 9 11
Time Complexity: O(N)
Attention reader! Don’t stop learning now. Get hold of all the important DSA concepts with the DSA Self Paced Course at a student-friendly price and become industry ready.