समस्या विवरण
इस ट्यूटोरियल में, हम सीखेंगे कि सिंगली लिंक्ड सूची से उन सभी नोड्स को कैसे हटाया जाए जिनका मान दिए गए x से बड़ा है।
हल करने के चरण
dataऔरnextपॉइंटर के साथ स्ट्रक्चर लिखें।- सिंगली लिंक्ड सूची में नोड डालने का फंक्शन लिखें।
- डमी डेटा के साथ सिंगली लिंक्ड सूची प्रारंभ करें।
- सिंगली लिंक्ड सूची पर पुनरावृति करें। वर्तमान नोड डेटा
xसे बड़ा है या नहीं, जांचें। - यदि वर्तमान डेटा
xसे बड़ा है, तो नोड को हटाएं। - नोड हटाने का फंक्शन लिखें। नोड हटाते समय निम्न तीन मामलों पर विचार करें:
- यदि नोड हेड नोड है, तो हेड को अगले नोड पर ले जाएं।
- यदि नोड मध्य नोड है, तो अगले नोड को पिछले नोड से लिंक करें।
- यदि नोड अंतिम नोड है, तो पिछले नोड लिंक को हटाएं।
C++ कोड उदाहरण
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
Node* next;
};
Node* getNewNode(int data) {
Node* newNode = new Node;
newNode->data = data;
newNode->next = NULL;
return newNode;
}
void deleteGreaterNodes(Node** head_ref, int x) {
Node *temp = *head_ref, *prev;
if (temp != NULL && temp->data > x) {
*head_ref = temp->next;
free(temp);
temp = *head_ref;
}
while (temp != NULL) {
while (temp != NULL && temp->data <= x) {
prev = temp;
temp = temp->next;
}
if (temp == NULL) {
return;
}
prev->next = temp->next;
delete temp;
temp = prev->next;
}
}
void printLinkedList(Node* head) {
while (head) {
cout << head->data << " -> ";
head = head->next;
}
}
int main() {
Node* head = getNewNode(1);
head->next = getNewNode(2);
head->next->next = getNewNode(3);
head->next->next->next = getNewNode(4);
head->next->next->next->next = getNewNode(5);
head->next->next->next->next->next = getNewNode(6);
int x = 3;
cout << "हटाने से पहले लिंक्ड सूची:" << endl;
printLinkedList(head);
deleteGreaterNodes(&head, x);
cout << "\nहटाने के बाद लिंक्ड सूची:" << endl;
printLinkedList(head);
return 0;
}
आउटपुट
हटाने से पहले लिंक्ड सूची: 1 -> 2 -> 3 -> 4 -> 5 -> 6 -> हटाने के बाद लिंक्ड सूची: 1 -> 2 -> 3 ->
निष्कर्ष
यदि ट्यूटोरियल में कोई प्रश्न हैं, तो उन्हें कमेंट सेक्शन में उल्लेख करें।