কম্পিউটার টিউটোরিয়াল

সি প্রোগ্রাম: সিংলি লিংকড লিস্টের নোডগুলোর যোগফল


একটি সিংলি লিংকড লিস্ট হল এমন ডেটা স্ট্রাকচার যেখানে প্রতিটি উপাদানের দুটি অংশ থাকে: একটি মান এবং অন্যটি পরবর্তী উপাদানের লিংক। সিংলি লিংকড লিস্টের সব উপাদানের যোগফল বের করতে হলে প্রতিটি নোডে নেভিগেট করে উপাদানের মান যোগফল ভেরিয়েবলে যোগ করতে হবে।

উদাহরণ

লিংকড লিস্ট: 2 -> 27 -> 32 -> 1 -> 5 যোগফল = 2 + 27 + 32 + 1 + 5 = 67।

এটি দুই পদ্ধতিতে করা যায়:

পদ্ধতি ১ - একটি লুপ ব্যবহার করে যা লিংকড লিস্টের সব মান 위로 লুপ করে এবং যোগফল বের করে। লুপ লিংকড লিস্টের শেষ পর্যন্ত চলে (যখন পয়েন্টার 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

পদ্ধতি ২ - একটি রিকার্সিভ ফাংশন ব্যবহার করে যা লিংকড লিস্টের উপাদান থাকা পর্যন্ত নিজেকে কল করে। রিকার্সিভ ফাংশন পরবর্তী নোডের মান এবং যোগফলের ঠিকানা প্যারামিটার হিসেবে পাঠায়।

উদাহরণ

#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

  1. লিংকড লিস্টের বিকল্প নোডগুলির গুণফল বের করা

  2. বাইনারি ট্রির গভীরতম নোডগুলোর যোগফল বের করা C++-এ

  3. সি++-এ সার্কুলার লিংকড লিস্টের নোডগুলোর যোগফল (Sum)

  4. সি++-এ লিংকড লিস্টের অল্টারনেট নোডগুলোর যোগফল