求給定單鏈表中前 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
廣告
資料結構
網路
RDBMS
作業系統
Java
iOS
HTML
CSS
Android
Python
C 程式設計
C++
C#
MongoDB
MySQL
Javascript
PHP