यहां, हमें एक लिंक्ड लिस्ट और एक इंडेक्स दिया गया है। हमें लिंक्ड लिस्ट में Nth नोड प्राप्त करने के लिए एक फंक्शन लिखना है।
आइए एक उदाहरण से समस्या को समझते हैं,
इनपुट
linked list = 34 -> 4 -> 9 -> 1, n = 2
आउटपुट
9
नोड पर जाने के लिए जिसे n द्वारा निर्दिष्ट किया गया है। हम लिंक्ड लिस्ट में नोड दर नोड जाएंगे और इंडेक्स काउंट को तब तक बढ़ाएंगे जब तक आवश्यक nth स्थिति नहीं पहुंच जाती।
प्रोग्राम जो प्रोग्राम को दर्शाता है,
उदाहरण
#include <iostream>
using namespace std;
class Node {
public:
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;
}
int findNodeAt(Node* head, int index) {
Node* current = head;
int count = 0;
while (current != NULL) {
if (count == index)
return(current->data);
count++;
current = current->next;
}
}
int main() {
Node* head = NULL;
insertNode(&head, 8);
insertNode(&head, 2);
insertNode(&head, 9);
insertNode(&head, 1);
insertNode(&head, 4);
int n = 2;
cout << "Element at index " << n << " is " << findNodeAt(head, 2);
return 0;
}
आउटपुट
Element at index 2 is 9