# Product of the nodes of a Singly Linked List

Given with n nodes the task is to print the product of all the nodes of a singly linked list. The program must traverse all the nodes of a singly linked list starting from the initial node till the NULL is not found.

## Example

Input -: 1 2 3 4 5
Output -: 120

In the above example, starting from first node all the nodes are traversed i.e 1, 2 3, 4, 5, 6 and their product is 1*2*3*4*5*6 = 120

## Approach used below is as follows

• Take a temporary pointer, lets say, temp of type node
• Set this temp pointer to first node which is pointed by head pointer
• Move temp to temp ->next while the temp is not NULL.
• Set product=product*(temp->data)

## Algorithm

Start
Step 1 -> create structure of a node and temp, next and head as pointer to a structure node
struct node
int data
End
Step 2 -> declare function to insert a node in a list
void insert(int val)
struct node* newnode = (struct node*)malloc(sizeof(struct node))
newnode->data = val
End
Else
Loop While temp->next!=NULL
Set temp=temp->next
End
Set newnode->next=NULL
Set temp->next=newnode
End
Step 3 -> Declare a function to display list
void display()
Print no node
End
Else
Loop While temp!=NULL
Print temp->data
Set temp=temp->next
End
End
Step 4 -> declare a function to find alternate nodes
void product_nodes()
declare int product=1
Loop While temp!=NULL
Set product=product * (temp->data)
Set temp=temp->next
End
Print product
Step 5 -> in main()
Create nodes using struct node* head = NULL;
Call function insert(10) to insert a node
Call display() to display the list
Call product_nodes() to find alternate nodes product
Stop

## Example

#include<stdio.h>
#include<stdlib.h>
//structure of a node
struct node{
int data;
struct node *next;
//function for inserting nodes into a list
void insert(int val){
struct node* newnode = (struct node*)malloc(sizeof(struct node));
newnode->data = val;
newnode->next = NULL;
} else {
temp->next=newnode;
temp=temp->next;
}
}
//function for displaying a list
void display(){
printf("no node ");
else{
while(temp!=NULL){
printf("%d ",temp->data);
temp=temp->next;
}
}
}
//function for finding product
void product_nodes(){
int product=1;
while(temp!=NULL){
product=product * (temp->data);
temp=temp->next;
}
printf("product of nodes is : %d" ,product);
}
int main(){
//creating list
//inserting elements into a list
insert(1);
insert(2);
insert(3);
insert(4);
insert(5);
insert(6);
//displaying the list
display();
//calling function for finding prodouct
Product_nodes();
return 0;
}

## Output

linked list is : 1 2 3 4 5 6
product of nodes is : 720

Updated on: 20-Sep-2019

222 Views