在C ++中找到给定链接列表的最后N个节点的乘积

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

这个过程很简单。我们只需从左侧开始读取当前元素,然后将这些元素添加到堆栈中即可。填充堆栈后,删除n个元素并将它们与prod相乘。(最初prod为1),当遍历n个元素时,则停止。

示例

#include<iostream>
#include<stack>
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 prodLastNElements(Node *start, int n) {
      if(n <= 0)
         return 0;
      stack<int> stk;
      long long res = 1;
      Node* temp = start;
      while (temp != NULL) {
         stk.push(temp->data);
         temp = temp->next;
      }
      while(n--){
         res *= stk.top();
         stk.pop();
      }
   return res;
}
int main() {
   Node *start = NULL;
   int arr[] = {5, 7, 3, 5, 6, 9};
   int size = sizeof(arr)/sizeof(arr[0]);
   int n = 3;
   for(int i = 0; i<size; i++){
      append(&start, arr[i]);
   }
   cout << "Product of last n elements: " << prodLastNElements(start, n);
}

输出结果

Product of last n elements: 270