इस ट्यूटोरियल में, हम सीखेंगे कि लिंक्ड लिस्ट में M नोड्स के बाद N नोड्स कैसे हटाए जाएं।
समस्या को हल करने के चरण देखते हैं।
लिंक्ड लिस्ट नोड के लिए एक स्ट्रक्चर 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) { // M नोड्स छोड़ें for (count = 1; count < M && current!= NULL; count++) { current = current->next; } // लिंक्ड लिस्ट का अंत if (current == NULL) { return; } // M नोड्स के बाद N नोड्स हटा रहे हैं 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
निष्कर्ष
यदि ट्यूटोरियल में आपके कोई प्रश्न हैं, तो उन्हें कमेंट सेक्शन में बताएं।