Get Node Value (Hackerrank)

Question: Given a pointer to the head of a linked list and a specific position, determine the data value at that position. Count backwards from the tail node. The tail is at position 0, its parent is at 1 and so on.


Function Description
Complete the getNode function 
getNode has the following parameters:
  • SinglyLinkedListNode pointer head: refers to the head of the list
  • int positionFromTail: the item to retrieve

Returns
int: the value at the desired position

So basically, they have given us a position from the tail value and want us to find the kth element from the tail. Mind you! The last value in a linked list is always NULL.

Let's begin! 

int getNode(SinglyLinkedListNode* head, int positionFromTail) {
     SinglyLinkedListNode* temp= head; //set temp as Head value

    int len=0;
    while(temp!=NULL)
    {
        len++;
        temp=temp->next;
    }
    temp=head;
    int pos=len-positionFromTail-1;
    int i=0;
    while(i<pos)
    {
        temp=temp->next;
        i++;
    }
    return temp->data;
    }

Here we set a temp node at head value, we then iterate through the linked list to find its length.
Once we know the length we use the Pos integer to find the kth element we need to output by implementing -> Pos= len- positionfromtail-1. This basically gives us the position of the kth element from the front excluding the NULL value. 

Once we have done this, we iterate another while loop to get to the kth element, Once we are at the kth element, we output its value as Temp->data.

And that kids is what i coded!

Popular posts from this blog

Finding the Subarrays (Hackerearth)

Palindrome Index (Hackerrank)

Sherlock and Array (Hackerrank)