परिचय
इस ट्यूटोरियल में हम सीखेंगे कि C++ में डबल लिंक्ड लिस्ट से दी गई पोजीशन (position) पर स्थित नोड को कैसे डिलीट किया जाता है। डबल लिंक्ड लिस्ट में पिछले नोड का एक्सेस होने के कारण डिलीट ऑपरेशन अधिक सरल होता है।
समस्या समाधान के चरण
- डेटा, prev और next पॉइंटर्स के साथ एक स्ट्रक्चर परिभाषित करें।
- डबल लिंक्ड लिस्ट में नोड डालने का फंक्शन लिखें।
- डमी डेटा के साथ लिस्ट को इनिशियलाइज़ करें।
- डिलीट करने के लिए पोजीशन इनिशियलाइज़ करें।
- लिंक्ड लिस्ट पर पुनरावृत्ति करें और दी गई पोजीशन वाले नोड को ढूंढें।
- नोड डिलीट करने का फंक्शन लिखते समय तीन स्थितियों पर विचार करें:
- यदि नोड हेड नोड है, तो हेड को अगले नोड पर ले जाएं।
- यदि नोड मध्य में है, तो अगले नोड को पिछले नोड से लिंक करें।
- यदि नोड अंतिम है, तो पिछले नोड का लिंक हटा दें।
उदाहरण कोड
#include <bits/stdc++.h>
using namespace std;
struct Node {
int data;
struct Node *prev, *next;
};
void deleteNode(struct Node** head_ref, struct Node* del) {
if (*head_ref == NULL || del == NULL) return;
// हेड नोड
if (*head_ref == del) *head_ref = del->next;
// मध्य नोड
if (del->next != NULL) del->next->prev = del->prev;
// अंतिम नोड
if (del->prev != NULL) del->prev->next = del->next;
free(del);
}
void deleteNodeAtGivenPosition(struct Node** head_ref, int n) {
if (*head_ref == NULL || n <= 0) return;
struct Node* current = *head_ref;
for (int i = 1; current != NULL && i < n; i++) {
current = current->next;
}
if (current == NULL) return;
deleteNode(head_ref, current);
}
void insertNode(struct Node** head_ref, int new_data) {
struct Node* new_node = (struct Node*)malloc(sizeof(struct Node));
new_node->data = new_data;
new_node->prev = NULL;
new_node->next = (*head_ref);
if ((*head_ref) != NULL) {
(*head_ref)->prev = new_node;
}
(*head_ref) = new_node;
}
void printLinkedList(struct Node* head) {
while (head != NULL) {
cout << head->data << "->";
head = head->next;
}
}
int main() {
struct Node* head = NULL;
insertNode(&head, 5);
insertNode(&head, 2);
insertNode(&head, 4);
insertNode(&head, 8);
insertNode(&head, 10);
cout << "Doubly linked list before deletion" << endl;
printLinkedList(head);
int n = 2;
deleteNodeAtGivenPosition(&head, n);
cout << "\nDoubly linked list after deletion" << endl;
printLinkedList(head);
return 0;
}
आउटपुट
Doubly linked list before deletion 10->8->4->2->5-> Doubly linked list after deletion 10->4->2->5->
निष्कर्ष
इस प्रोग्राम में हमने डबल लिंक्ड लिस्ट से दी गई पोजीशन (2) पर स्थित नोड को सफलतापूर्वक डिलीट किया। डबल लिंक्ड लिस्ट में डिलीट ऑपरेशन अधिक कुशल है क्योंकि हमें पिछले नोड को खोजने के लिए ट्रैवर्स नहीं करना पड़ता। यदि आपके कोई प्रश्न हैं, तो कमेंट सेक्शन में पूछें।