C语言单链表节点求和


单链表是一种数据结构,其中每个元素包含两部分:值和指向下一个元素的链接。因此,要找到单链表所有元素的和,必须遍历链表的每个节点,并将元素的值添加到一个求和变量中。

例如

Suppose we have a linked list: 2 -> 27 -> 32 -> 1 -> 5
sum = 2 + 27 + 32 + 1 + 5 = 67.

这可以通过两种方法完成:

方法一 - 使用循环遍历链表的所有值并求和。

循环运行到链表结尾,即当某个元素的指针指向空时,此循环将运行并找到每个元素值的和。

示例

#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

方法二 - 使用递归函数,该函数会一直调用自身,直到链表中没有元素为止。递归函数会反复调用自身。对递归函数的调用会将下一个节点的值以及和的地址位置作为参数发送。

Explore our latest online courses and learn new skills at your own pace. Enroll and become a certified expert to boost your career.

示例

#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

更新于:2019年8月9日

4K+ 次浏览

开启您的职业生涯

完成课程获得认证

开始学习
广告