Sum and Product of the nodes of a Circular Singly Linked List which are divisible by K
Given a singly circular linked list. The task is to find the sum and product of nodes that are divisible by K of the given linked list.
Input : List = 5->6->7->8->9->10->11->11 K = 11 Output : Sum = 22, Product = 121 Input : List = 15->7->3->9->11->5 K = 5 Output : Product = 75, Sum = 20
- Initialize a pointer current with the head of the circular linked list and a sum variable sum with 0 and a product variable product with 1.
- Start traversing the linked list using a do-while loop until all the nodes get traversed.
- If current node data is divisible by the given key.
- Add the value of current node to the sum i.e. sum = sum + current -> data.
- Multiply the value of the current node to the product i.e. product = product * current -> data.
- Increment the pointer to the next node of the linked list i.e. temp = temp -> next.
- Print the sum and product.
Below is the implementation of the above approach:
Initial List: 5 6 7 8 9 10 11 11 Sum = 22, Product = 121
Time Complexity: O(n), as we are using a loop to traverse n times. Where n is the number of nodes in the linked list.
Auxiliary Space: O(1), as we are not using any extra space.