Computer >> 컴퓨터 >  >> 프로그램 작성 >> C++

C++에서 순환 연결 목록의 노드 합계


이 문제에서는 순환 연결 목록이 제공됩니다. 우리의 임무는 순환 연결 목록의 노드 합계를 찾는 프로그램을 만드는 것입니다.

연결 리스트의 모든 노드 값을 추가하기만 하면 됩니다.

몇 가지 중요한 정의

  • Linked List는 링크를 통해 서로 연결된 일련의 데이터 구조입니다.

C++에서 순환 연결 목록의 노드 합계

  • 순환 연결 목록은 첫 번째 요소가 마지막 요소를 가리키고 마지막 요소가 첫 번째 요소를 가리키는 연결 목록의 변형입니다. 단일 연결 목록과 이중 연결 목록은 모두 순환 연결 목록으로 만들 수 있습니다.

C++에서 순환 연결 목록의 노드 합계

이제 문제를 이해하기 위해 예를 들어보겠습니다.

입력

14 -> 1 -> 7 -> 9 -> 2 -> 6

출력

39

설명

sum = 14 + 1 + 7 + 9 + 2 + 6 = 39

이 문제를 해결하기 위해 연결 목록을 탐색합니다. 그리고 각 노드의 값을 합계 변수에 추가합니다. 그런 다음 전체 목록을 순회할 때 합계를 반환합니다.

알고리즘

1단계 - sum =0 및 sumPointer =

초기화

2단계 - do-while sumPointer !=머리. 하세요

2.1단계 − sum에 현재 노드의 값을 더합니다. 즉, sum +=sumPointer → value입니다.

2.2단계 − 다음 노드에 대한 포인터 증가, 즉 sumPointer =sumPointer → next.

3단계 − 반환 합계.

예시

솔루션을 설명하는 프로그램,

#include <iostream>
using namespace std;
struct Node {
   int data;
   struct Node* next;
};
void pushNode(struct Node** head_ref, int data) {
   struct Node* ptr1 = (struct Node*)malloc(sizeof(struct Node));
   struct Node* temp = *head_ref;
   ptr1->data = data;
   ptr1->next = *head_ref;
   if (*head_ref != NULL) {
      while (temp->next != *head_ref)
         temp = temp->next;
         temp->next = ptr1;
   }
   else
      ptr1->next = ptr1;
      *head_ref = ptr1;
}
int CalcSumCirList(struct Node* head) {
   struct Node* sumPointer = head;
   int sum = 0;
   if (head != NULL) {
      do {
         sumPointer = sumPointer->next;
         sum += sumPointer->data;
      }
       while (sumPointer != head);
   }
   return sum;
}
int main(){
   struct Node* head = NULL;
   pushNode(&head, 4);
   pushNode(&head, 7);
   pushNode(&head, 12);
   pushNode(&head, 1);
   pushNode(&head, 9);
   pushNode(&head, 6);
   cout<<"The sum of Circular linked list is "<<CalcSumCirList(head);
   return 0;
}

출력

The sum of Circular linked list is 39