Suma y producto de Nodes con valor como suma de dígitos pares en la lista circular enlazada

Dada una lista circular 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: Lista = 15 -> 16 -> 8 -> 6 -> 13 
Salida: Suma = 42, Producto = 9360 
Explicación: 
La lista enlazada circular contiene: 
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: Lista = 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

Acercarse:  

  1. Inicialice un puntero actual con el encabezado de la lista circular enlazada y una suma variable suma con 0 y una variable producto producto con 1.
  2. Comience a recorrer la lista enlazada utilizando un bucle do-while hasta que se atraviesen todos los Nodes.
  3. Si el valor de los datos del Node actual tiene una suma de dígitos pares. 
    • Agregue el valor del Node actual a la suma, es decir , sum = sum + current -> data .
    • Multiplique el valor del Node actual por el producto, es decir , producto = producto * actual -> datos .
    • Incremente el puntero al siguiente Node de la lista enlazada, es decir, temp = temp -> next .
  4. Imprime la suma y el producto.

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

C++

// C++ implementation to find the sum and
// product of all of the Even Digit sum nodes
// in a circularly linked list
#include <bits/stdc++.h>
using namespace std;
 
// Circular list node
struct Node {
    int data;
    struct Node* next;
};
 
// Function to find the digit sum
// for a number
int digitSum(int num)
{
    int sum = 0;
    while (num) {
        sum += (num % 10);
        num /= 10;
    }
 
    return sum;
}
 
// Function to calculate sum and
// product
void SumProduct(struct Node* head,
                int key)
{
    struct Node* current = head;
 
    int sum = 0, product = 1;
 
    // If list is empty simply
    // show message
    if (head == NULL) {
        printf("\nList is empty\n");
        return;
    }
    // Traverse first to last node
    else {
        do {
            // Check if current node's
            // data has an even digit sum
            if (!(digitSum(current->data)
                  & 1))
            {
 
                // Calculate sum
                sum += current->data;
 
                // Calculate product
                product *= current->data;
            }
 
            current = current->next;
        } while (current != head);
    }
 
    cout << "Sum = " << sum
        << ", Product = " << product;
}
 
// Function print the list
void DisplayList(struct Node* head)
{
    struct Node* current = head;
 
    // If list is empty simply
    // show message
    if (head == NULL)
    {
        printf("\nList is empty\n");
        return;
    }
    // Traverse first to last node
    else {
        do {
            printf("%d ", current->data);
            current = current->next;
        } while (current != head);
    }
}
 
// Function to insert a node at the
// end of a Circular linked list
void InsertNode(struct Node** head,
                int data)
{
    struct Node* current = *head;
     
    // Create a new node
    struct Node* newNode = new Node;
 
    // Check node is created or not
    if (!newNode) {
        printf("\nMemory Error\n");
        return;
    }
 
    // Insert data into newly
    // created node
    newNode->data = data;
 
    // Check list is empty
    // if not have any node then
    // make first node it
    if (*head == NULL) {
        newNode->next = newNode;
        *head = newNode;
        return;
    }
    // If list have already some node
    else {
 
        // Move first node to last
        // node
        while (current->next != *head)
        {
            current = current->next;
        }
 
        // Put first or head node
        // address in new node link
        newNode->next = *head;
 
        // Put new node address into
        // last node link(next)
        current->next = newNode;
    }
}
 
// Driver Code
int main()
{
    struct Node* head = NULL;
    InsertNode(&head, 13);
    InsertNode(&head, 6);
    InsertNode(&head, 8);
    InsertNode(&head, 15);
    InsertNode(&head, 16);
 
    cout << "Initial List: ";
    DisplayList(head);
 
    cout << endl;
    SumProduct(head, 11);
 
    return 0;
}

Java

// Java implementation to find the sum and
// product of all of the Even Digit sum nodes
// in a circularly linked list
class GFG{
 
// Structure for a node
static class Node{
    int data;
    Node next;
}
 
// Function to calculate the sum of
// individual digits
static int digitSum(int n)
{
    int sum = 0;
    while (n != 0)
    {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}
 
// Function to calculate sum and
// product
static void SumProduct(Node head)
{
    Node temp = head;
    int Sum = 0;
    int Prod = 1;
     
    do
    {
         
        // Check if current node's
        // data has an even digit sum
        if (digitSum(temp.data) % 2 == 0)
        {
            Sum += temp.data;
            Prod *= temp.data;
        }
 
        temp = temp.next;
 
    } while (temp != head);
 
    System.out.print("Sum = " + Sum);
    System.out.print(", Product = " + Prod);
}
 
// Function print the list
static void DisplayList(Node head)
{
    Node temp = head;
    if (head != null)
    {
        do
        {
             
            // Traverse first to last node
            System.out.print(temp.data + " ");
            temp = temp.next;
        } while (temp != head);
    }
    System.out.println();
}
 
// Function to insert a node at the ending
// of a Circular linked list
static Node InsertNode(int key, Node head)
{
 
    // Create a new node
    Node new_node = new Node();
    new_node.data = key;
 
    // If linked list is null then
    // make the first node as head
    // after insertion
    if (head == null)
    {
        head = new_node;
        new_node.next = head;
 
    }
    else
    {
         
        // traverse to the end and insert
        // node at the end and make
        // it point to the head
        Node temp = head;
        while (temp.next != head)
        {
            temp = temp.next;
        }
         
        temp.next = new_node;
        new_node.next = head;
    }
    return head;
}
 
// Driver code
public static void main(String args[])
{
    Node head = null;
     
    head = InsertNode(13, head);
    head = InsertNode(6, head);
    head = InsertNode(8, head);
    head = InsertNode(15, head);
    head = InsertNode(16, head);
     
    System.out.print("Initial List: ");
     
    DisplayList(head);
    SumProduct(head);
}
}
 
// This code is contributed by nishkarsh146

Python3

# Python3 implementation to find the
# sum and product of all of the Even
# Digit sum nodes in a circularly
# linked list
 
# Circular list node
class Node:
     
    def __init__(self, x):
         
        self.data = x
        self.next = None
 
# Function to find the digit sum
# for a number
def digitSum(num):
     
    sum = 0
     
    while (num):
        sum += (num % 10)
        num //= 10
         
    return sum
 
# Function to calculate sum and
# product
def SumProduct(head, key):
     
    current = head
    sum = 0
    product = 1
 
    # If list is empty simply
    # show message
    if (head == None):
        print("List is empty")
        return
     
    # Traverse first to last node
    else:
        while (True):
             
            # Check if current node's
            # data has an even digit sum
            if (not (digitSum(current.data) & 1)):
 
                # Calculate sum
                sum += current.data
 
                # Calculate product
                product *= current.data
 
            current = current.next
 
            if current == head:
                break
 
    print("Sum =", sum,
          ", Product = ", product)
 
# Function print the list
def DisplayList(head):
     
    current = head
 
    # If list is empty simply
    # show message
    if (head == None):
        print("List is empty\n")
        return
     
    # Traverse first to last node
    else:
        while True:
            print(current.data, end = " ")
            current = current.next
 
            if current == head:
                break
 
# Function to insert a node at the
# end of a Circular linked list
def InsertNode(head, data):
     
    current = head
 
    # Create a new node
    newNode = Node(data)
 
    # Check node is created or not
    if (not newNode):
        print("Memory Error")
        return
 
    # Check list is empty
    # if not have any node then
    # make first node it
    if (head == None):
        newNode.next = newNode
        head = newNode
        return head
         
    # If list have already some node
    else:
 
        # Move first node to last
        # node
        while (current.next != head):
            current = current.next
 
        # Put first or head node
        # address in new node link
        newNode.next = head
 
        # Put new node address into
        # last node link(next)
        current.next = newNode
 
    return head
 
# Driver Code
if __name__ == '__main__':
     
    head = None
    head = InsertNode(head, 13)
    head = InsertNode(head, 6)
    head = InsertNode(head, 8)
    head = InsertNode(head, 15)
    head = InsertNode(head, 16)
 
    print("Initial List: ", end = " ")
 
    DisplayList(head)
 
    print()
    SumProduct(head, 11)
     
# This code is contributed by mohit kumar 29

C#

// C# implementation to find the sum and
// product of all of the Even Digit sum nodes
// in a circularly linked list
using System;
 
class GFG{
 
// Structure for a node
class Node
{
    public int data;
    public Node next;
}
 
// Function to calculate the sum of
// individual digits
static int digitSum(int n)
{
    int sum = 0;
    while (n != 0)
    {
        sum += n % 10;
        n /= 10;
    }
    return sum;
}
 
// Function to calculate sum and
// product
static void SumProduct(Node head)
{
    Node temp = head;
    int Sum = 0;
    int Prod = 1;
     
    do
    {
         
        // Check if current node's
        // data has an even digit sum
        if (digitSum(temp.data) % 2 == 0)
        {
            Sum += temp.data;
            Prod *= temp.data;
        }
 
        temp = temp.next;
 
    } while (temp != head);
 
    Console.Write("Sum = " + Sum);
    Console.Write(", Product = " + Prod);
}
 
// Function print the list
static void DisplayList(Node head)
{
    Node temp = head;
    if (head != null)
    {
        do
        {
             
            // Traverse first to last node
            Console.Write(temp.data + " ");
            temp = temp.next;
        } while (temp != head);
    }
    Console.WriteLine();
}
 
// Function to insert a node at the ending
// of a Circular linked list
static Node InsertNode(int key, Node head)
{
 
    // Create a new node
    Node new_node = new Node();
    new_node.data = key;
 
    // If linked list is null then
    // make the first node as head
    // after insertion
    if (head == null)
    {
        head = new_node;
        new_node.next = head;
 
    }
    else
    {
         
        // traverse to the end and insert
        // node at the end and make
        // it point to the head
        Node temp = head;
        while (temp.next != head)
        {
            temp = temp.next;
        }
         
        temp.next = new_node;
        new_node.next = head;
    }
    return head;
}
 
// Driver code
public static void Main(String []args)
{
    Node head = null;
     
    head = InsertNode(13, head);
    head = InsertNode(6, head);
    head = InsertNode(8, head);
    head = InsertNode(15, head);
    head = InsertNode(16, head);
     
    Console.Write("Initial List: ");
     
    DisplayList(head);
    SumProduct(head);
}
}
 
// This code is contributed by 29AjayKumar

Javascript

<script>
// Javascript implementation to find the sum and
// product of all of the Even Digit sum nodes
// in a circularly linked list
class Node
{
    data;
    next;
     
}
 
// Function to calculate the sum of
// individual digits
function digitSum(n)
{
    let sum = 0;
    while (n != 0)
    {
        sum += n % 10;
        n = Math.floor(n/10);
    }
    return sum;
}
 
// Function to calculate sum and
// product
function SumProduct(head)
{
    let temp = head;
    let Sum = 0;
    let Prod = 1;
      
    do
    {
          
        // Check if current node's
        // data has an even digit sum
        if (digitSum(temp.data) % 2 == 0)
        {
            Sum += temp.data;
            Prod *= temp.data;
        }
  
        temp = temp.next;
  
    } while (temp != head);
  
    document.write("Sum = " + Sum);
    document.write(", Product = " + Prod);
}
 
// Function print the list
function DisplayList(head)
{
    let temp = head;
    if (head != null)
    {
        do
        {
              
            // Traverse first to last node
            document.write(temp.data + " ");
            temp = temp.next;
        } while (temp != head);
    }
    document.write("<br>");
}
 
// Function to insert a node at the ending
// of a Circular linked list
function InsertNode(key,head)
{
    // Create a new node
    let new_node = new Node();
    new_node.data = key;
  
    // If linked list is null then
    // make the first node as head
    // after insertion
    if (head == null)
    {
        head = new_node;
        new_node.next = head;
  
    }
    else
    {
          
        // traverse to the end and insert
        // node at the end and make
        // it point to the head
        let temp = head;
        while (temp.next != head)
        {
            temp = temp.next;
        }
          
        temp.next = new_node;
        new_node.next = head;
    }
    return head;
}
 
// Driver code
let head = null;
      
head = InsertNode(13, head);
head = InsertNode(6, head);
head = InsertNode(8, head);
head = InsertNode(15, head);
head = InsertNode(16, head);
document.write("Initial List: ");
DisplayList(head);
SumProduct(head);
 
// This code is contributed by patel2127
</script>
Producción: 

Initial List: 13 6 8 15 16 
Sum = 42, Product = 9360

 

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 *