একটি সার্কুলার লিংকড লিস্ট দেওয়া আছে। সব নোডের ডেটার যোগফল বের করতে হবে।
ইনপুট
14 -> 1 -> 7 -> 9 -> 2 -> 6 (circular)
আউটপুট
39
ব্যাখ্যা — 14+1+7+9+2+6 = 39
এলগরিদম
CalcSumCirList(head):
sum = 0, ptr = head
if head != NULL:
do:
ptr = ptr->next
sum += ptr->data
while ptr != head
return sum
উদাহরণ কোড
#include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
void pushNode(Node** head, int data){
Node* ptr1 = (Node*)malloc(sizeof(Node));
Node* temp = *head;
ptr1->data = data; ptr1->next = *head;
if(*head != NULL){
while(temp->next != *head) temp = temp->next;
temp->next = ptr1;
} else ptr1->next = ptr1;
*head = ptr1;
}
int CalcSumCirList(Node* head){
Node* ptr = head; int sum = 0;
if(head != NULL){
do{
ptr = ptr->next;
sum += ptr->data;
} while(ptr != head);
}
return sum;
}
int main(){
Node* head = NULL;
pushNode(&head, 4); pushNode(&head, 7);
pushNode(&head, 12); pushNode(&head, 1);
pushNode(&head, 9); pushNode(&head, 6);
cout << "Sum: " << CalcSumCirList(head);
return 0;
}
আউটপুট
The sum of Circular linked list is 39