以 C++ 找出給定連結串列最後 N 個節點乘積


考慮我們有一個連結串列中的幾個元素。我們必須找出最後 n 個元素的乘法結果。n 的值也已給出。因此,如果連結串列為 [5, 7, 3, 5, 6, 9],並且 n = 3,那麼結果將為 5 * 6 * 9 = 270。

流程很簡單。我們只需從左側開始讀取當前元素,然後將這些元素新增到 stack 中。Stack 裝滿後,移除 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

更新: 2019-11-04

107 次瀏覽

開啟您的職業生涯

完成課程獲得認證

入門
廣告