Open In App

Sum and Product of all even digit sum Nodes of a Singly Linked List

Improve
Improve
Like Article
Like
Save
Share
Report

Given a singly linked list containing N nodes, the task is to find the sum and product of all the nodes from the list whose data value has an even digit sum.

Examples:  

Input: 15 -> 16 -> 8 -> 6 -> 13 
Output: 
Sum = 42 
Product = 9360 
Explanation: 
The sum of all digit of number in linked list are: 
15 = 1 + 5 = 6 
16 = 1 + 6 = 7 
8 = 8 
6 = 6 
13 = 1 + 3 = 4 
The list contains 4 Even Digit Sum data values 15, 8, 6 and 13. 
Sum = 15 + 8 + 6 + 13 = 42 
Product = 15 * 8 * 6 * 13 = 9360

Input: 5 -> 3 -> 4 -> 2 -> 9 
Output: 
Sum = 6 
Product = 8 
Explanation: 
The list contains 2 Even Digit Sum data values 4 and 2. 
Sum = 4 + 2 = 6 
Product = 4 * 2 = 8 

Approach: The idea is to traverse the given linked list and check whether the sum of all the digits of current node value is even or not. If yes include the current node value to the resultant sum and the resultant product Else check for the next node value.

Below is the implementation of the above approach:  

C++




// C++ program for the above approach
 
#include <bits/stdc++.h>
using namespace std;
 
// Node of Linked List
struct Node {
    int data;
    Node* next;
};
 
// Function to insert a node at the
// beginning of the singly Linked List
void push(Node** head_ref, int new_data)
{
    // Allocate new node
    Node* new_node
        = (Node*)malloc(
            sizeof(struct Node));
 
    // Insert the data
    new_node->data = new_data;
 
    // Link old list to the new node
    new_node->next = (*head_ref);
 
    // Move head to point the new node
    (*head_ref) = new_node;
}
 
// Function to find the digit sum
// for a number
int digitSum(int num)
{
    int sum = 0;
    while (num) {
        sum += (num % 10);
        num /= 10;
    }
 
    // Return the sum
    return sum;
}
 
// Function to find the required
// sum and product
void sumAndProduct(Node* head_ref)
{
 
    // Initialise the sum and product
    // to 0 and 1 respectively
    int prod = 1;
    int sum = 0;
 
    Node* ptr = head_ref;
 
    // Traverse the given linked list
    while (ptr != NULL) {
 
        // If current node has even
        // digit sum then include it in
        // resultant sum and product
        if (!(digitSum(ptr->data) & 1)) {
 
            // Find the sum and the product
            prod *= ptr->data;
            sum += ptr->data;
        }
 
        ptr = ptr->next;
    }
 
    // Print the final Sum and Product
    cout << "Sum = " << sum << endl;
    cout << "Product = " << prod;
}
 
// Driver Code
int main()
{
    // Head of the linked list
    Node* head = NULL;
 
    // Create the linked list
    // 15 -> 16 -> 8 -> 6 -> 13
    push(&head, 13);
    push(&head, 6);
    push(&head, 8);
    push(&head, 16);
    push(&head, 15);
 
    // Function call
    sumAndProduct(head);
 
    return 0;
}


Java




// Java program for the above approach
 
class GFG{
 
// Node of Linked List
static class Node {
    int data;
    Node next;
};
 
// Function to insert a node at the
// beginning of the singly Linked List
static Node push(Node head_ref, int new_data)
{
    // Allocate new node
    Node new_node
        = new Node();
 
    // Insert the data
    new_node.data = new_data;
 
    // Link old list to the new node
    new_node.next = head_ref;
 
    // Move head to point the new node
    head_ref = new_node;
    return head_ref;
}
 
// Function to find the digit sum
// for a number
static int digitSum(int num)
{
    int sum = 0;
    while (num > 0) {
        sum += (num % 10);
        num /= 10;
    }
 
    // Return the sum
    return sum;
}
 
// Function to find the required
// sum and product
static void sumAndProduct(Node head_ref)
{
 
    // Initialise the sum and product
    // to 0 and 1 respectively
    int prod = 1;
    int sum = 0;
 
    Node ptr = head_ref;
 
    // Traverse the given linked list
    while (ptr != null) {
 
        // If current node has even
        // digit sum then include it in
        // resultant sum and product
        if ((digitSum(ptr.data) %2 != 1)) {
 
            // Find the sum and the product
            prod *= ptr.data;
            sum += ptr.data;
        }
 
        ptr = ptr.next;
    }
 
    // Print the final Sum and Product
    System.out.print("Sum = " + sum +"\n");
    System.out.print("Product = " + prod);
}
 
// Driver Code
public static void main(String[] args)
{
    // Head of the linked list
    Node head = null;
 
    // Create the linked list
    // 15.16.8.6.13
    head = push(head, 13);
    head = push(head, 6);
    head = push(head, 8);
    head = push(head, 16);
    head = push(head, 15);
 
    // Function call
    sumAndProduct(head);
 
}
}
 
// This code is contributed by 29AjayKumar


Python3




# Python3 program for the above approach
 
# Node of Linked List
class Node:
     
    def __init__(self, x):
         
        self.data = x
        self.next = None
 
# Function to insert a node at the
# beginning of the singly Linked List
def push(head_ref, new_data):
     
    # Insert the data
    new_node = Node(new_data)
 
    # Link old list to the new node
    new_node.next = head_ref
 
    # Move head to point the new node
    head_ref = new_node
 
    return head_ref
 
# Function to find the digit sum
# for a number
def digitSum(num):
     
    sum = 0
     
    while (num):
        sum += (num % 10)
        num //= 10
 
    # Return the sum
    return sum
 
# Function to find the required
# sum and product
def sumAndProduct(head_ref):
 
    # Initialise the sum and product
    # to 0 and 1 respectively
    prod = 1
    sum = 0
 
    ptr = head_ref
 
    # Traverse the given linked list
    while (ptr != None):
 
        # If current node has even
        # digit sum then include it in
        # resultant sum and product
        if (not (digitSum(ptr.data) & 1)):
 
            # Find the sum and the product
            prod *= ptr.data
            sum += ptr.data
 
        ptr = ptr.next
 
    # Print the final Sum and Product
    print("Sum =", sum)
    print("Product =", prod)
 
# Driver Code
if __name__ == '__main__':
     
    # Head of the linked list
    head = None
 
    # Create the linked list
    # 15 . 16 . 8 . 6 . 13
    head = push(head, 13)
    head = push(head, 6)
    head = push(head, 8)
    head = push(head, 16)
    head = push(head, 15)
 
    # Function call
    sumAndProduct(head)
     
# This code is contributed by mohit kumar 29


C#




// C# program for the above approach
using System;
 
class GFG{
 
// Node of Linked List
class Node
{
    public int data;
    public Node next;
};
 
// Function to insert a node at the
// beginning of the singly Linked List
static Node push(Node head_ref, int new_data)
{
    // Allocate new node
    Node new_node = new Node();
 
    // Insert the data
    new_node.data = new_data;
 
    // Link old list to the new node
    new_node.next = head_ref;
 
    // Move head to point the new node
    head_ref = new_node;
    return head_ref;
}
 
// Function to find the digit sum
// for a number
static int digitSum(int num)
{
    int sum = 0;
    while (num > 0)
    {
        sum += (num % 10);
        num /= 10;
    }
 
    // Return the sum
    return sum;
}
 
// Function to find the required
// sum and product
static void sumAndProduct(Node head_ref)
{
 
    // Initialise the sum and product
    // to 0 and 1 respectively
    int prod = 1;
    int sum = 0;
 
    Node ptr = head_ref;
 
    // Traverse the given linked list
    while (ptr != null)
    {
 
        // If current node has even
        // digit sum then include it in
        // resultant sum and product
        if ((digitSum(ptr.data) % 2 != 1))
        {
 
            // Find the sum and the product
            prod *= ptr.data;
            sum += ptr.data;
        }
 
        ptr = ptr.next;
    }
 
    // Print the readonly Sum and Product
    Console.Write("Sum = " + sum + "\n");
    Console.Write("Product = " + prod);
}
 
// Driver Code
public static void Main(String[] args)
{
    // Head of the linked list
    Node head = null;
 
    // Create the linked list
    // 15.16.8.6.13
    head = push(head, 13);
    head = push(head, 6);
    head = push(head, 8);
    head = push(head, 16);
    head = push(head, 15);
 
    // Function call
    sumAndProduct(head);
 
}
}
 
// This code is contributed by Rohit_ranjan


Javascript




<script>
// javascript program for the above approach
    // Node of Linked List
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
 
    // Function to insert a node at the
    // beginning of the singly Linked List
    function push(head_ref , new_data) {
        // Allocate new node
var new_node = new Node();
 
        // Insert the data
        new_node.data = new_data;
 
        // Link old list to the new node
        new_node.next = head_ref;
 
        // Move head to point the new node
        head_ref = new_node;
        return head_ref;
    }
 
    // Function to find the digit sum
    // for a number
    function digitSum(num) {
        var sum = 0;
        while (num > 0) {
            sum += (num % 10);
            num = parseInt(num/10);
        }
 
        // Return the sum
        return sum;
    }
 
    // Function to find the required
    // sum and product
    function sumAndProduct(head_ref) {
 
        // Initialise the sum and product
        // to 0 and 1 respectively
        var prod = 1;
        var sum = 0;
 
var ptr = head_ref;
 
        // Traverse the given linked list
        while (ptr != null) {
 
            // If current node has even
            // digit sum then include it in
            // resultant sum and product
            if ((digitSum(ptr.data) % 2 != 1)) {
 
                // Find the sum and the product
                prod *= ptr.data;
                sum += ptr.data;
            }
 
            ptr = ptr.next;
        }
 
        // Print the final Sum and Product
        document.write("Sum = " + sum + "<br/>");
        document.write("Product = " + prod);
    }
 
    // Driver Code
     
        // Head of the linked list
var head = null;
 
        // Create the linked list
        // 15.16.8.6.13
        head = push(head, 13);
        head = push(head, 6);
        head = push(head, 8);
        head = push(head, 16);
        head = push(head, 15);
 
        // Function call
        sumAndProduct(head);
 
 
// This code contributed by gauravrajput1
</script>


Output

Sum = 42
Product = 9360









Time Complexity: O(N), where N is the number of nodes in the linked list.
Auxiliary Space: O(1)

Recursive Approach:

  • Create a recursive function that takes a pointer to the head of the linked list, the sum and the product as arguments.
  • If the head pointer is NULL, return the sum and the product.
  • Calculate the digit sum of the data of the current node.
  • If the digit sum is even, update the sum and the product accordingly.
  • Recursively call the function with the next node in the linked list, the updated sum, and the updated product.
  • Return the final sum and product.
     

Below is the implementation of the above approach:

C++




#include <bits/stdc++.h>
using namespace std;
 
// Node of Linked List
struct Node {
    int data;
    Node* next;
};
 
// Function to insert a node at the
// beginning of the singly Linked List
void push(Node** head_ref, int new_data)
{
    // Allocate new node
    Node* new_node = new Node();
 
    // Insert the data
    new_node->data = new_data;
 
    // Link old list to the new node
    new_node->next = (*head_ref);
 
    // Move head to point the new node
    (*head_ref) = new_node;
}
 
// Function to find the digit sum
// for a number
int digitSum(int num)
{
    int sum = 0;
    while (num) {
        sum += (num % 10);
        num /= 10;
    }
 
    // Return the sum
    return sum;
}
 
// Recursive function to find the sum and product
// of nodes with even digit sum in a linked list
void sumAndProductHelper(Node* ptr, int& prod, int& sum)
{
    // Base case: if the current node is null, return
    if (ptr == NULL) {
        return;
    }
 
    // Recursive call on the next node
    sumAndProductHelper(ptr->next, prod, sum);
 
    // If the current node has even digit sum,
    // update the product and sum
    if (!(digitSum(ptr->data) & 1)) {
        prod *= ptr->data;
        sum += ptr->data;
    }
}
 
// Wrapper function to call the recursive function
void sumAndProduct(Node* head_ref)
{
    // Initialise the sum and product to 0 and 1 respectively
    int prod = 1;
    int sum = 0;
 
    // Call the recursive function on the head node
    sumAndProductHelper(head_ref, prod, sum);
 
    // Print the final Sum and Product
    cout << "Sum = " << sum << endl;
    cout << "Product = " << prod;
}
 
// Driver Code
int main()
{
    // Head of the linked list
    Node* head = NULL;
 
    // Create the linked list
    // 15 -> 16 -> 8 -> 6 -> 13
    push(&head, 13);
    push(&head, 6);
    push(&head, 8);
    push(&head, 16);
    push(&head, 15);
 
    // Function call
    sumAndProduct(head);
 
    return 0;
}


Java




// Node class for Linked List
class Node {
    int data;
    Node next;
 
    Node(int data) {
        this.data = data;
        this.next = null;
    }
}
 
public class Main {
    // Function to insert a node at the
    // beginning of the singly Linked List
    static Node push(Node head, int newData) {
        // Allocate new node
        Node newNode = new Node(newData);
 
        // Link old list to the new node
        newNode.next = head;
 
        // Move head to point to the new node
        return newNode;
    }
 
    // Function to find the digit sum for a number
    static int digitSum(int num) {
        int sum = 0;
        while (num > 0) {
            sum += num % 10;
            num /= 10;
        }
 
        // Return the sum
        return sum;
    }
 
    // Recursive function to find the sum and product
    // of nodes with even digit sum in a linked list
    static void sumAndProductHelper(Node ptr, int[] prodSum) {
        // Base case: if the current node is null, return
        if (ptr == null) {
            return;
        }
 
        // Recursive call on the next node
        sumAndProductHelper(ptr.next, prodSum);
 
        // If the current node has even digit sum,
        // update the product and sum
        if ((digitSum(ptr.data) & 1) == 0) {
            prodSum[0] *= ptr.data;
            prodSum[1] += ptr.data;
        }
    }
 
    // Wrapper function to call the recursive function
    static void sumAndProduct(Node head) {
        // Initialize the sum and product to 0 and 1 respectively
        int[] prodSum = {1, 0};
 
        // Call the recursive function on the head node
        sumAndProductHelper(head, prodSum);
 
        // Print the final Sum and Product
        System.out.println("Sum = " + prodSum[1]);
        System.out.println("Product = " + prodSum[0]);
    }
 
    // Driver Code
    public static void main(String[] args) {
        // Head of the linked list
        Node head = null;
 
        // Create the linked list
        // 15 -> 16 -> 8 -> 6 -> 13
        head = push(head, 13);
        head = push(head, 6);
        head = push(head, 8);
        head = push(head, 16);
        head = push(head, 15);
 
        // Function call
        sumAndProduct(head);
    }
}


Python




# Node of Linked List
class Node:
    def __init__(self, data):
        self.data = data
        self.next = None
 
# Function to insert a node at the
# beginning of a singly Linked List
 
 
def push(head_ref, new_data):
    # Create a new node
    new_node = Node(new_data)
 
    # Link old list to the new node
    new_node.next = head_ref[0]
 
    # Move head to point to the new node
    head_ref[0] = new_node
 
# Function to find the digit sum for a number
 
 
def digit_sum(num):
    _sum = 0
    while num:
        _sum += num % 10
        num //= 10
 
    # Return the sum
    return _sum
 
# Recursive function to find the sum and product
# of nodes with even digit sum in a linked list
 
 
def sum_and_product_helper(ptr, prod, _sum):
    # Base case: if the current node is None, return
    if ptr is None:
        return
 
    # Recursive call on the next node
    sum_and_product_helper(ptr.next, prod, _sum)
 
    # If the current node has an even digit sum,
    # update the product and sum
    if not digit_sum(ptr.data) & 1:
        prod[0] *= ptr.data
        _sum[0] += ptr.data
 
# Wrapper function to call the recursive function
 
 
def sum_and_product(head_ref):
    # Initialize the sum and product to 0 and 1, respectively
    prod = [1]
    _sum = [0]
 
    # Call the recursive function on the head node
    sum_and_product_helper(head_ref[0], prod, _sum)
 
    # Print the final Sum and Product
    print("Sum =", _sum[0])
    print("Product =", prod[0])
 
 
# Driver Code
if __name__ == "__main__":
    # Head of the linked list
    head = [None]
 
    # Create the linked list
    # 15 -> 16 -> 8 -> 6 -> 13
    push(head, 13)
    push(head, 6)
    push(head, 8)
    push(head, 16)
    push(head, 15)
 
    # Function call
    sum_and_product(head)


C#




using System;
 
// Node of Linked List
public class Node
{
    public int data;
    public Node next;
}
public class GFG
{
    // Function to insert a node at the beginning of the singly Linked List
    public static void Push(ref Node head_ref, int new_data)
    {
        // Allocate new node
        Node new_node = new Node();
        // Insert the data
        new_node.data = new_data;
        // Link old list to the new node
        new_node.next = head_ref;
        // Move head to point to the new node
        head_ref = new_node;
    }
    // Function to find the digit sum for a number
    public static int DigitSum(int num)
    {
        int sum = 0;
        while (num != 0)
        {
            sum += (num % 10);
            num /= 10;
        }
        // Return the sum
        return sum;
    }
    // Recursive function to find the sum and product of nodes with even digit sum in a linked list
    public static void SumAndProductHelper(Node ptr, ref int prod, ref int sum)
    {
        // Base case: if the current node is null, return
        if (ptr == null)
        {
            return;
        }
        // Recursive call on the next node
        SumAndProductHelper(ptr.next, ref prod, ref sum);
        // If the current node has even digit sum and update the product and sum
        if ((DigitSum(ptr.data) & 1) == 0)
        {
            prod *= ptr.data;
            sum += ptr.data;
        }
    }
    // Wrapper function to call the recursive function
    public static void SumAndProduct(Node head_ref)
    {
        // Initialize the sum and product to 0 and 1 respectively
        int prod = 1;
        int sum = 0;
        // Call the recursive function on the head node
        SumAndProductHelper(head_ref, ref prod, ref sum);
        // Print the final Sum and Product
        Console.WriteLine("Sum = " + sum);
        Console.WriteLine("Product = " + prod);
    }
    // Driver Code
    public static void Main(string[] args)
    {
        // Head of the linked list
        Node head = null;
        // Create the linked list 15 -> 16 -> 8 -> 6 -> 13
        Push(ref head, 13);
        Push(ref head, 6);
        Push(ref head, 8);
        Push(ref head, 16);
        Push(ref head, 15);
        // Function call
        SumAndProduct(head);
    }
}


Javascript




// Node of Linked List
class Node {
    constructor(data) {
        this.data = data;
        this.next = null;
    }
}
 
// Function to insert a node at the
// beginning of the singly Linked List
function push(head_ref, new_data) {
    // Allocate new node
    let new_node = new Node(new_data);
 
    // Link old list to the new node
    new_node.next = head_ref;
 
    // Move head to point the new node
    head_ref = new_node;
    return head_ref;
}
 
// Function to find the digit sum
// for a number
function digitSum(num) {
    let sum = 0;
    while (num) {
        sum += (num % 10);
        num = Math.floor(num / 10);
    }
 
    // Return the sum
    return sum;
}
 
// Recursive function to find the sum and product
// of nodes with even digit sum in a linked list
function sumAndProductHelper(ptr, prod, sum) {
    // Base case: if the current node is null, return
    if (ptr == null) {
        return;
    }
 
    // Recursive call on the next node
    sumAndProductHelper(ptr.next, prod, sum);
 
    // If the current node has even digit sum,
    // update the product and sum
    if (!(digitSum(ptr.data) & 1)) {
        prod[0] *= ptr.data;
        sum[0] += ptr.data;
    }
}
 
// Wrapper function to call the recursive function
function sumAndProduct(head_ref) {
    // Initialise the sum and product to 0 and 1 respectively
    let prod = [1];
    let sum = [0];
 
    // Call the recursive function on the head node
    sumAndProductHelper(head_ref, prod, sum);
 
    // Print the final Sum and Product
    console.log("Sum = " + sum[0]);
    console.log("Product = " + prod[0]);
}
 
// Driver Code
 
// Head of the linked list
let head = null;
 
// Create the linked list
// 15 -> 16 -> 8 -> 6 -> 13
head = push(head, 13);
head = push(head, 6);
head = push(head, 8);
head = push(head, 16);
head = push(head, 15);
 
// Function call
sumAndProduct(head);


Output

Sum = 42
Product = 9360









Time Complexity: O(n), where n is the number of nodes in the linked list.
Space Complexity: O(n), where n is the number of nodes in the linked list. This is because for each recursive call.



Last Updated : 19 Oct, 2023
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads