# Modify Linked List by replacing each node by nearest multiple of K

Modify Linked List by replacing each node by nearest multiple of KGiven a singly Linked List L consisting of N nodes and an integer K, the task is to modify the value of each node of the given Linked List to its nearest multiple of K, not exceeding the value of the node.Examples:Input: LL: 1 -> 2 -> 3 -> 5, K = 2 Output: 0 -> 2 -> 2 -> 4Explanation:The resultant LL has values having less than the original LL value and is a multiple of K(= 2).Input: LL:13 -> 14 -> 26 -> 29 -> 40, K = 13Output: 13 -> 13 -> 26 -> 26 -> 39Approach: The given problem can be solved by traversing the given Linked List and for each node traversed, find the floor value, say val, of the node value divided by K and update the node values to val*K.Below is the implementation of the above approach:C++ #include using namespace std; struct node { int data; node* next;}; node* EvalNearestMult(node* N, int K){ node* temp = N; int t; while (N != NULL) { if (N->data < K) N->data = 0; else { if (N->data == K) N->data = K; else { N->data = (N->data / K) * K; } } N = N->next; } return temp;} void printList(node* N){ while (N != NULL) { cout data next; }} int main(){ node* head = NULL; node* second = NULL; node* third = NULL; head = new node(); second = new node(); third = new node(); head->data = 3; head->next = second; second->data = 4; second->next = third; third->data = 8; third->next = NULL; node* t = EvalNearestMult(head, 3); printList(t); return 0;}Output:

3 3 6

Time Complexity: O(N)Auxiliary Space: O(1)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.