C程序中单链接列表的节点总和
单链列表是一种数据结构,其中元素具有两个部分,一个是值,另一个是到下一个元素的链接。因此,要查找单链列表的所有元素的总和,我们必须导航到链列表的每个节点,并将元素的值添加到sum变量中。
例如
Suppose we have a linked list: 2 -> 27 -> 32 -> 1 -> 5 sum = 2 + 27 + 32 + 1 + 5 = 67.
这可以通过使用两种方法来完成:
方法1- 使用循环遍历链接列表的所有值并找到总和的循环。
该循环一直运行到链表的末尾,即当元素的指针指向null时,此循环将运行并查找每个元素的值之和。
示例
#include <iostream>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push(struct Node** nodeH, int nodeval) {
struct Node* new_node = new Node;
new_node->data = nodeval;
new_node->next = (*nodeH);
(*nodeH) = new_node;
}
int main() {
struct Node* head = NULL;
int sum = 0;
push(&head, 95);
push(&head, 60);
push(&head, 87);
push(&head, 6);
push(&head, 12);
struct Node* ptr = head;
while (ptr != NULL) {
sum += ptr->data;
ptr = ptr->next;
}
cout << "Sum of nodes = "<< sum;
return 0;
}输出结果
Sum of nodes = 260
方法2-使用一个递归函数进行调用,直到链接列表包含元素为止。递归函数一次又一次地调用自身。对递归函数的调用将下一个节点值作为参数与总和地址位置一起发送。
示例
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node* next;
};
void push(struct Node** head_ref, int new_data) {
struct Node* new_node = new Node;
new_node->data = new_data;
new_node->next = (*head_ref);
(*head_ref) = new_node;
}
void nodesum(struct Node* head, int* sum) {
if (!head)
return;
nodesum(head->next, sum);
*sum = *sum + head->data;
}
int main() {
struct Node* head = NULL;
int sum= 0;
push(&head, 95);
push(&head, 60);
push(&head, 87);
push(&head, 6);
push(&head, 12);
nodesum(head,&sum);
cout << "Sum of nodes = "<<sum;
return 0;
}输出结果
Sum of nodes = 260