📜  循环链表中偶数和的节点的总和和乘积

📅  最后修改于: 2021-09-05 11:36:03             🧑  作者: Mango

给定一个包含N 个节点的循环单向链表,任务是从列表中找到其数据值具有偶数和的所有节点的和和乘积。

例子:

方法:

  1. 用循环链表的头部初始化一个指针 current,用 0 初始化一个 sum 变量sum ,用 1 初始化一个 product 变量product
  2. 开始使用 do-while 循环遍历链表,直到遍历所有节点。
  3. 如果当前节点数据值具有偶数和。
    • 将当前节点的值添加到总和中,即sum = sum + current -> data
    • 将当前节点的值乘以产品即product = product * current -> data
    • 增加指向链表下一个节点的指针,即temp = temp -> next
  4. 打印总和和乘积。

下面是上述方法的实现:

C++
// C++ implementation to find the sum and
// product of all of the Even Digit sum nodes
// in a circularly linked list
#include 
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 calulate the sum of
// indivdual 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 calulate the sum of
// indivdual 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


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

如果您想与行业专家一起参加直播课程,请参阅Geeks Classes Live