Suma y producto de todos los Nodes de suma de dígitos pares de una lista enlazada simple

Dada una lista enlazada individualmente que contiene N Nodes, la tarea es encontrar la suma y el producto de todos los Nodes de la lista cuyo valor de datos tiene una suma de dígitos pares.

Ejemplos:  

Entrada: 15 -> 16 -> 8 -> 6 -> 13 
Salida: 
Suma = 42 
Producto = 9360 
Explicación: 
La suma de todos los dígitos del número en la lista enlazada es: 
15 = 1 + 5 = 6 
16 = 1 + 6 = 7 
8 = 8 
6 = 6 
13 = 1 + 3 = 4 
La lista contiene 4 valores de datos de suma de dígitos pares 15, 8, 6 y 13. 
Suma = 15 + 8 + 6 + 13 = 42 
Producto = 15 * 8 * 6 * 13 = 9360

Entrada: 5 -> 3 -> 4 -> 2 -> 9 
Salida: 
Suma = 6 
Producto = 8 
Explicación: 
La lista contiene 2 valores de datos de suma de dígitos pares 4 y 2. 
Suma = 4 + 2 = 6 
Producto = 4 * 2 = 8 

Enfoque: la idea es recorrer la lista enlazada dada y verificar si la suma de todos los dígitos del valor del Node actual es par o no. En caso afirmativo, incluya el valor del Node actual en la suma resultante y el producto resultante. De lo contrario, verifique el valor del siguiente Node.

A continuación se muestra la implementación del enfoque anterior:  

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>
Producción: 

Sum = 42
Product = 9360

 

Complejidad de tiempo: O(N) , donde N es el número de Nodes en la lista enlazada.

Espacio Auxiliar: O(1)
 

Publicación traducida automáticamente

Artículo escrito por muskan_garg y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA

Deja una respuesta

Tu dirección de correo electrónico no será publicada. Los campos obligatorios están marcados con *