在C ++中找到给定链接列表的前k个节点的乘积

考虑一下,链表中的元素很少。我们必须找到前k个元素的相乘结果。k的值也被给出。因此,如果列表类似于[5、7、3、5、6、9],并且k = 3,则结果将是5 * 7 * 3 = 105。

流程很简单。我们只需从左侧开始读取当前元素,然后将其乘以prod。(最初prod为1),当遍历k个元素时,则停止。

示例

#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);
}

输出结果

Product of first k elements: 105