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 divisible by K.
Input : 12->15->9->11->5->6->7 K = 3 Output : 11 -> 5 -> 7 Input :13->4->16->9->22->45->5->16->6 K = 4 Output : 13 -> 9 -> 22 -> 45 -> 5 -> 6
The approach to solving this problem is similar to deleting all nodes from the list which are lesser than the given key.
There are two possible cases:
- Head node holds a value divisible by K: First check for all occurrences at head node which are divisible by K, delete them and change the head node appropriately.
- Some intermediate node holds value divisible by k: Start traversing from head and check if current node’s value is divisible by 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 7 Final List: 11 5 7
Don’t stop now and take your learning to the next level. Learn all the important concepts of Data Structures and Algorithms with the help of the most trusted course: DSA Self Paced. Become industry ready at a student-friendly price.
- Delete all nodes from the doubly linked list which are divisible by K
- Sum of all nodes in a doubly linked list divisible by a given number K
- Product of all nodes in a doubly linked list divisible by a given number K
- Delete N nodes after M nodes of a linked list
- Delete all the nodes from the list which are less than K
- Delete all the nodes from the list that are greater than x
- Delete all the even nodes of a Circular Linked List
- Delete all the even nodes from a Doubly Linked List
- Delete all odd nodes of a Circular Linked List
- Delete alternate nodes of a Linked List
- Delete continuous nodes with sum K from a given linked list
- Program to delete all even nodes from a Singly Linked List
- Delete all Prime Nodes from a Singly Linked List
- Delete all odd or even positioned nodes from Circular Linked List
- Delete all Prime Nodes from a Doubly Linked List
- Delete all Non-Prime Nodes from a Singly Linked List
- Delete all the nodes from the doubly linked list that are greater than a given value
- Delete all the nodes from a doubly linked list that are smaller than a given value
- Delete linked list nodes which have a Lesser Value on Left Side
- Delete all Prime Nodes from a Circular Singly Linked List
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to firstname.lastname@example.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.
Improved By : princiraj1992