Modify Linked List by replacing each node by nearest multiple of K | C ++ program for the above approach ; Structure of node ; Function to replace the node N by the nearest multiple of K ; Traverse the Linked List ; If data is less than K ; If the data of current node is same as K ; Otherwise change the value ; Move to the next node ; Return the updated LL ; Function to print the nodes of the Linked List ; Traverse the LL ; Print the node 's data ; Driver Code ; Given Linked List
#include <iostream> NEW_LINE 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 << N -> data << " ▁ " ; N = N -> 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 ; }