এই টিউটোরিয়ালে আমরা একটি প্রোগ্রাম লিখব যা দেওয়া লিংকড লিস্টকে p:q অনুপাতে ভাগ করবে।
এটি একটি সরল প্রোগ্রাম। সমাধানের ধাপগুলো:
লিংকড লিস্ট নোডের জন্য একটি struct তৈরি করুন।
ডামি ডেটা দিয়ে লিংকড লিস্ট ইনিশিয়ালাইজ করুন।
p:q অনুপাত ইনিশিয়ালাইজ করুন।
লিংকড লিস্টের দৈর্ঘ্য বের করুন।
যদি লিংকড লিস্টের দৈর্ঘ্য p + q এর চেয়ে কম হয়, তবে এটি p:q অনুপাতে ভাগ করা সম্ভব নয়।
অন্যথায় লিংকড লিস্টকে p পয়ন্ত ইটারেট করুন।
p ইটারেশনের পর লিংকটি সরিয়ে দ্বিতীয় লিংকড লিস্টের জন্য একটি নতুন হেড তৈরি করুন।
এখন লিংকড লিস্টের দুটি অংশ প্রিন্ট করুন।
উদাহরণ
নিচে কোডটি দেওয়া হলো:
#include<bits/stdc++.h> using namespace std; struct Node { int data; Node *next; Node(int data) { this->data = data; this->next = NULL; } }; void printLinkedList(Node* head) { Node *temp = head; while (temp) { cout << temp->data << " -> "; temp = temp->next; } cout << "NULL" << endl; } void splitLinkedList(Node *head, int p, int q) { int n = 0; Node *temp = head; // finding the length of the linked list while (temp != NULL) { n += 1; temp = temp->next; } // checking wether we can divide the linked list or not if (p + q > n) { cout << "Can't divide Linked list" << endl; } else { temp = head; while (p > 1) { temp = temp->next; p -= 1; } // second head node after splitting Node *head_two = temp->next; temp->next = NULL; // printing linked lists printLinkedList(head); printLinkedList(head_two); } } int main() { Node* head = new Node(1); head->next = new Node(2); head->next->next = new Node(3); head->next->next->next = new Node(4); head->next->next->next->next = new Node(5); head->next->next->next->next->next = new Node(6); int p = 2, q = 4; splitLinkedList(head, p, q); }আউটপুট
উপরের কোডটি রান করলে নিচের ফলাফল পাওয়া যাবে:
1 -> 2 -> NULL 3 -> 4 -> 5 -> 6 -> NULL
উপসংহার
টিউটোরিয়াল সম্পর্কে কোনো প্রশ্ন থাকলে কমেন্ট সেকশনে জানান।