Danh sách liên kết đơn: mỗi nút chứa giá trị và con trỏ đến nút tiếp theo. Tổng các phần tử = duyệt qua từng nút và cộng dồn.
Ví dụ
Danh sách: 2 → 27 → 32 → 1 → 5
Tổng = 2 + 27 + 32 + 1 + 5 = 67
Phương pháp 1: Vòng lặp
#include <iostream>
using namespace std;
struct Node {
int data;
Node* next;
};
void push(Node** head, int val) {
Node* newNode = new Node;
newNode->data = val;
newNode->next = *head;
*head = newNode;
}
int main() {
Node* head = NULL;
int sum = 0;
push(&head, 95);
push(&head, 60);
push(&head, 87);
push(&head, 6);
push(&head, 12);
Node* ptr = head;
while (ptr != NULL) {
sum += ptr->data;
ptr = ptr->next;
}
cout << "Tong cac nut = " << sum;
return 0;
}
Phương pháp 2: Đệ quy
void nodeSum(Node* head, int* sum) {
if (!head) return;
nodeSum(head->next, sum);
*sum += head->data;
}
Kết quả
Tong cac nut = 260