단일 연결 목록은 요소가 두 부분으로 구성된 데이터 구조입니다. 하나는 값이고 다른 하나는 다음 요소에 대한 링크입니다. 따라서 단일 연결 목록의 모든 요소의 합을 찾으려면 연결 목록의 각 노드로 이동하여 요소 값을 합 변수에 추가해야 합니다.
예를 들어
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