Find the product of first k nodes of the given Linked List in C++

C++Server Side ProgrammingProgramming

Consider we have few elements in a linked list. We have to find the multiplication result of first k number of elements. The value of k is also given. So if the list is like [5, 7, 3, 5, 6, 9], and k = 3, then result will be 5 * 7 * 3 = 105.

The processes is straight forward. We simply read the current element starting from left side, then multiply it with the prod. (initially prod is 1), when k number of elements are traversed, then stop.

Example

#include<iostream>
#include<cmath>
using namespace std;
   class Node{
      public:
         int data;
         Node *next;
   };
   Node* getNode(int data){
      Node *newNode = new Node;
      newNode->data = data;
      newNode->next = NULL;
      return newNode;
   }
   void append(struct Node** start, int key) {
      Node* new_node = getNode(key);
      Node *p = (*start);
      if(p == NULL){
         (*start) = new_node;
         return;
   }
   while(p->next != NULL){
      p = p->next;
   }
   p->next = new_node;
}
long long prodFirstKElements(Node *start, int k) {
   long long res = 1;
   int count = 0;
   Node* temp = start;
   while (temp != NULL && count != k) {
      res *= temp->data;
      count++;
      temp = temp->next;
   }
   return res;
   }
int main() {
   Node *start = NULL;
   int arr[] = {5, 7, 3, 5, 6, 9};
   int n = sizeof(arr)/sizeof(arr[0]);
   int k = 3;
   for(int i = 0; i<n; i++){
   append(&start, arr[i]);
}
cout << "Product of first k elements: " << prodFirstKElements(start, k);
}

Output

Product of first k elements: 105
raja
Published on 04-Nov-2019 12:47:25
Advertisements