Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> C++

Chương trình C++ tính tích N nút cuối của danh sách liên kết

Cho danh sách liên kết có vài phần tử. Tìm tích của n phần tử cuối. Giá trị n cũng cho trước. Nếu danh sách [5, 7, 3, 5, 6, 9] và n = 3, kết quả = 5 * 6 * 9 = 270.

Quy trình đơn giản: đọc phần tử từ đầu, đẩy vào stack. Sau khi đầy stack, lấy n phần tử và nhân vào tích (khởi tạo 1), dừng khi đã duyệt n phần tử.

Ví dụ mã nguồ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);
}

Kết quả đầu ra

Product of last n elements: 270