मान लें हमारे पास लिंक्ड लिस्ट में कुछ तत्व हैं। हमें अंतिम 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 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