এই টিউটোরিয়ালে আমরা শিখব কিভাবে একটি লিংকড লিস্টে M নোডের পর N নোড ডিলিট করা যায়।
সমস্যা সমাধানের ধাপগুলো:
লিংকড লিস্ট নোডের জন্য একটি struct Node লিখুন।
ডামি ডেটা দিয়ে লিংকড লিস্ট ইনিশিয়ালাইজ করুন।
M নোডের পর N নোড ডিলিট করার ফাংশন লিখুন।
হেড পয়েন্টারের সাথে একটি পয়েন্টার ইনিশিয়ালাইজ করুন।
লিংকড লিস্টের শেষ পর্যন্ত ইটারেট করুন।
পয়েন্টারকে M নোড পর্যন্ত নেক্সট নোডে সরিয়ে আনুন।
N নোড ডিলিট করুন
পয়েন্টারকে নেক্সট নোডে সরিয়ে আনুন
লিংকড লিস্ট প্রিন্ট করুন
উদাহরণ
নিচে কোডটি দেওয়া হলো:
#include <bits/stdc++.h> using namespace std; struct Node { int data; Node *next; }; void insertNode(Node ** head_ref, int new_data) { Node* new_node = new Node(); new_node->data = new_data; new_node->next = (*head_ref); *head_ref = new_node; } void printLinkedList(Node *head) { Node *temp = head; while (temp != NULL) { cout<< temp->data << " -> "; temp = temp->next; } cout << "Null" << endl; } void deleteNNodesAfterMNodes(Node *head, int M, int N) { Node *current = head, *temp; int count; while (current) { // skip M nodes for (count = 1; count < M && current!= NULL; count++) { current = current->next; } // end of the linked list if (current == NULL) { return; } // deleting N nodes after M nodes temp = current->next; for (count = 1; count <= N && temp != NULL; count++) { Node *deletingNode = temp; temp = temp->next; free(deletingNode); } current->next = temp; current = temp; } } int main() { Node* head = NULL; int M = 1, N = 2; insertNode(&head, 1); insertNode(&head, 2); insertNode(&head, 3); insertNode(&head, 4); insertNode(&head, 5); insertNode(&head, 6); insertNode(&head, 7); insertNode(&head, 8); insertNode(&head, 9); cout << "Linked list before deletion: "; printLinkedList(head); deleteNNodesAfterMNodes(head, M, N); cout << "Linked list after deletion: "; printLinkedList(head); return 0; }আউটপুট
উপরের কোডটি রান করলে নিচের ফলাফল পাওয়া যাবে:
Linked list before deletion: 9 -> 8 -> 7 -> 6 -> 5 -> 4 -> 3 -> 2 -> 1 -> Null Linked list after deletion: 9 -> 6 -> 3 -> Null
উপসংহার
টিউটোরিয়াল সম্পর্কে কোনো প্রশ্ন থাকলে কমেন্ট সেকশনে জানান।