รายการที่เชื่อมโยงอย่างเดียวคือโครงสร้างข้อมูลที่องค์ประกอบมีสองส่วน หนึ่งคือค่า และอีกส่วนหนึ่งคือลิงก์ไปยังองค์ประกอบถัดไป ดังนั้น ในการหาผลรวมขององค์ประกอบทั้งหมดของรายการที่เชื่อมโยงโดยลำพัง เราต้องไปยังแต่ละโหนดของรายการที่เชื่อมโยง และเพิ่มค่าขององค์ประกอบลงในตัวแปรผลรวม
ตัวอย่าง
Suppose we have a linked list: 2 -> 27 -> 32 -> 1 -> 5 sum = 2 + 27 + 32 + 1 + 5 = 67.
ซึ่งสามารถทำได้โดยใช้สองวิธี:
วิธีที่ 1 - ใช้การวนซ้ำที่วนซ้ำค่าทั้งหมดของรายการที่เชื่อมโยงและหาผลรวม
การวนซ้ำทำงานจนถึงจุดสิ้นสุดของรายการที่เชื่อมโยง เช่น เมื่อตัวชี้ขององค์ประกอบชี้ไปที่ค่าว่าง การวนซ้ำนี้จะทำงานและค้นหาผลรวมของค่าของแต่ละองค์ประกอบ
ตัวอย่าง
#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