// https://www.geeksforgeeks.org/write-a-function-to-get-nth-node-in-a-linked-list/
#include <iostream>
#include <list>
using namespace std;
struct linked_list {
int data;
struct linked_list* next;
};
typedef struct linked_list node;
node* insert (node* head, int n) {
node* list = (node*)malloc(sizeof(node*));
list->data=n;
list->next=head;
head=list;
return head;
}
int search (node* head, int n) {
if (head!=NULL && n == 0)
return head->data;
node* list=head->next;
n--;
while (n>0 && list!=NULL) {
list=list->next;
n--;
}
if (list != NULL)
return list->data;
return -1;
}
int main () {
int n;
node* head;
while (true) {
cout<< "Enter the element, enter -9 to stop: ";
cin>>n;
if (n==-9)
break;
else
head = insert(head,n);
}
cout<< "Enter the index of the node: ";
cin >> n;
n=search(head, n);
if (n==-1)
cout<< "Index not found!";
else
cout<< "Element is "<<n;
}