ronith
7/6/2018 - 5:50 PM

Write a function to get Nth node in a Linked List

Write a GetNth() function that takes a linked list and an integer index and returns the data value stored in the node at that index position.

Example:

Input: 1->10->30->14, index = 2 Output: 30
The node at index 2 is 30

// 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;
}