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
方法二 - 使用遞迴函式,該函式會一直呼叫自身,直到連結串列中沒有元素為止。遞迴函式會反覆呼叫自身。對遞迴函式的呼叫會將下一個節點的值以及和的地址位置作為引數傳送。
示例
#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
廣告