Произведение узлов односвязного списка

Опубликовано: 24 Января, 2022

Учитывая односвязный список. Задача состоит в том, чтобы найти произведение всех узлов данного связного списка.
Примеры :

 Ввод : Список = 7-> 6-> 8-> 4-> 1
Выход : Продукт = 1344
Произведение узлов: 7 * 6 * 8 * 4 * 1 = 1344

Ввод : Список = 1-> 7-> 3-> 9-> 11-> 5
Выход : Продукт = 10395

Рекомендуется: сначала попробуйте свой подход в {IDE}, прежде чем переходить к решению.

Алгоритм :

  1. Инициализируйте указатель ptr с заголовком связанного списка и переменной продукта с 1.
  2. Начните обход связанного списка с помощью цикла, пока не пройдут все узлы.
  3. Умножьте значение текущего узла на продукт, т.е. product * = ptr -> data .
  4. Увеличивает указатель на следующий узел связанного списка, т.е. ptr = ptr -> next .
  5. Повторяйте два вышеуказанных шага до тех пор, пока не будет достигнут конец связанного списка.
  6. Наконец, верните товар.

Below is the implementation of above algorithm: 
 

C++

// C++ implementation to find the product of
// nodes of the Linked List
 
#include <iostream>
using namespace std;
 
// A Linked list node
struct Node {
    int data;
    struct Node* next;
};
 
// Function to insert a node at the
// beginning of the linked list
void push(struct Node** head_ref, int new_data)
{
    /* allocate node */
    struct Node* new_node = new Node;
 
    /* put in the data */
    new_node->data = new_data;
 
    /* link the old list to the new node */
    new_node->next = (*head_ref);
 
    /* move the head to point to the new node */
    (*head_ref) = new_node;
}
 
// Function to find the product of
// nodes of the given linked list
int productOfNodes(struct Node* head)
{
    // Pointer to traverse the list
    struct Node* ptr = head;
 
    int product = 1; // Variable to store product
 
    // Traverse the list and
    // calculate the product
    while (ptr != NULL) {
 
        product *= ptr->data;
        ptr = ptr->next;
    }
 
    // Return the product
    return product;
}
 
// Driver Code
int main()
{
    struct Node* head = NULL;
 
    // create linked list 7->6->8->4->1
    push(&head, 7);
    push(&head, 6);
    push(&head, 8);
    push(&head, 4);
    push(&head, 1);
 
    cout << "Product = " << productOfNodes(head);
 
    return 0;
}

Java

// Java implementation to find the product of
// nodes of the Linked List
class GFG
{
 
// A Linked list node
static class Node
{
    int data;
    Node next;
};
 
// Function to insert a node at the
// beginning of the linked list
static Node push( Node head_ref, int new_data)
{
    // allocate node /
    Node new_node = new Node();
 
    // put in the data /
    new_node.data = new_data;
 
    // link the old list to the new node /
    new_node.next = (head_ref);
 
    // move the head to point to the new node /
    (head_ref) = new_node;
    return head_ref;
}
 
// Function to find the product of
// nodes of the given linked list
static int productOfNodes( Node head)
{
    // Pointer to traverse the list
    Node ptr = head;
 
    int product = 1; // Variable to store product
 
    // Traverse the list and
    // calculate the product
    while (ptr != null)
    {
 
        product *= ptr.data;
        ptr = ptr.next;
    }
 
    // Return the product
    return product;
}
 
// Driver Code
public static void main(String args[])
{
    Node head = null;
 
    // create linked list 7.6.8.4.1
    head = push(head, 7);
    head = push(head, 6);
    head = push(head, 8);
    head = push(head, 4);
    head = push(head, 1);
 
    System.out.println("Product = " + productOfNodes(head));
}
}
 
// This code is contributed by Arnab Kundu

Python3

# Python3 implementation to find the product of
# nodes of the Linked List
import math
 
# A linked List node
class Node:
    def __init__(self,data):
        self.data = data
        self.next = None
 
# Function to insert a node at the
# beginning of the linked list
def push(head,data):
    if not head:
 
        # Return new node
        return Node(data)
     
    # allocate node
    new_node = Node(data)
     
    # link the old list to the new node
    new_node.next = head
     
    # move the head to point to the new node
    head = new_node
    return head
 
# Function to find the product of
# nodes of the given linked list
def productOfNodes(head):
     
    # Pointer to traverse the list
    ptr = head
    product = 1 # Variable to store product
 
    # Traverse the list and
    # calculate the product
    while(ptr):
        product *= ptr.data
        ptr = ptr.next
         
    # Return the product    
    return product
 
# Driver Code
if __name__=="__main__":
    head = None
 
    # create linked list 7->6->8->4->1
    head = push(head,7)
    head = push(head,6)
    head = push(head,8)
    head = push(head,4)
    head = push(head,1)
    print("Product = {}".format(productOfNodes(head)))
 
# This Code is Contribute By Vikash Kumar 37

C#

// C# implementation to find the product of
// nodes of the Linked List
using System;
 
class GFG
{
 
// A Linked list node
public class Node
{
    public int data;
    public Node next;
};
 
// Function to insert a node at the
// beginning of the linked list
static Node push(Node head_ref, int new_data)
{
    // allocate node /
    Node new_node = new Node();
 
    // put in the data /
    new_node.data = new_data;
 
    // link the old list to the new node /
    new_node.next = (head_ref);
 
    // move the head to point to the new node /
    (head_ref) = new_node;
    return head_ref;
}
 
// Function to find the product of
// nodes of the given linked list
static int productOfNodes( Node head)
{
    // Pointer to traverse the list
    Node ptr = head;
 
    int product = 1; // Variable to store product
 
    // Traverse the list and
    // calculate the product
    while (ptr != null)
    {
        product *= ptr.data;
        ptr = ptr.next;
    }
 
    // Return the product
    return product;
}
 
// Driver Code
public static void Main(String []args)
{
    Node head = null;
 
    // create linked list 7.6.8.4.1
    head = push(head, 7);
    head = push(head, 6);
    head = push(head, 8);
    head = push(head, 4);
    head = push(head, 1);
 
    Console.WriteLine("Product = " +
                       productOfNodes(head));
}
}
 
// This code is contributed by Rajput-Ji

Javascript

<script>
// javascript implementation to find the product of
// nodes of the Linked List    
// A Linked list node
class Node {
    constructor(val) {
        this.data = val;
        this.next = null;
    }
}
 
    // Function to insert a node at the
    // beginning of the linked list
    function push(head_ref , new_data) {
        // allocate node /
var new_node = new Node();
 
        // put in the data /
        new_node.data = new_data;
 
        // link the old list to the new node /
        new_node.next = (head_ref);
 
        // move the head to povar to the new node /
        (head_ref) = new_node;
        return head_ref;
    }
 
    // Function to find the product of
    // nodes of the given linked list
    function productOfNodes(head) {
        // Pointer to traverse the list
var ptr = head;
 
        var product = 1; // Variable to store product
 
        // Traverse the list and
        // calculate the product
        while (ptr != null) {
 
            product *= ptr.data;
            ptr = ptr.next;
        }
 
        // Return the product
        return product;
    }
 
    // Driver Code
     
var head = null;
 
        // create linked list 7.6.8.4.1
        head = push(head, 7);
        head = push(head, 6);
        head = push(head, 8);
        head = push(head, 4);
        head = push(head, 1);
 
        document.write("Product = " + productOfNodes(head));
 
// This code contributed by aashish1995
</script>
Output: 

Product = 1344