# Hackerrank Get Node Value Solution

Problem Statement
This challenge is part of a tutorial track by MyCodeSchool
You’re given the pointer to the head node of a linked list and a specific position. Counting backwards from the tail node of the linked list, get the value of the node at the given position. A position of 0 corresponds to the tail, 1 corresponds to the node before the tail and so on.

## Solution:

`````` /*
Get Nth element from the end in a linked list of integers
Number of elements in the list will always be greater than N.
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
{
// This is a "method-only" submission.
// You only need to complete this method.
int n = 0;
while(cur!=NULL){
n++;
cur = cur->next;
}
n --;
while(cur!=NULL){
if(n == positionFromTail){
return cur->data;
}
n--;
cur = cur ->next;
}
return 0;
}
``````

** The above solution is my own code and it may not be the optimal solution or optimal way to approach the problem but it passes all the testcases in Hackerrank. So if you have any optimal approaches feel free to paste the code as the comment below..... :) :) :)

int n;
while(l->next!=NULL)
{
n++;
l=l->next;
}
for(int i=0;i<(n-positionFromTail);i++)
{
r=r->next;
}
return r->data;
}

2. This comment has been removed by a blog administrator.

3. This comment has been removed by the author.

4. It is showing Compile time error But i think it to be correct

/*
Get Nth element from the end in a linked list of integers
Number of elements in the list will always be greater than N.
Node is defined as
struct Node
{
int data;
struct Node *next;
}
*/
{
Node *save = new Node;
int i =0;
while(save->next!=NULL){
save = save->next;
i++;
}