Search code examples
cfunctionreturnreturn-valuereturn-type

Get node value in linkedlist from end in c


I am doing this hackerrank question (https://www.hackerrank.com/challenges/get-the-value-of-the-node-at-a-specific-position-from-the-tail) My code is as follows -

int GetNode(Node *head,int positionFromTail)
{
  Node *prev = NULL;
  Node *current = head;
  Node *next;
  while(current!=NULL){
     next = current->next;
     current->next = prev;
     prev = current;
     current = next;
  }
  head = prev;
  int p=0;
  while(head->next!=NULL){
    if(p== positionFromTail){
        return head->data;
    }
    else {
        p++;
        head= head->next;
    }
  } 
}

So what i have done is, I have first reversed the linkedlist and then looped for the specific position and then printed its value. Is it correct method to do it? It gives me this error.

  solution.cc: In function ‘int GetNode(Node*, int)’:
  solution.cc:42:1: error: control reaches end of non-void function [Werror=return-type]
   }
   ^
   cc1plus: some warnings being treated as errors

Solution

  • Each possible branch which might leave the function needs to return a value.

    If the initial head->next would be NULL the return statement you coded would not be reached.

    Design your code to have a function have only one possible exit-point.

    This might look like the following:

    /* returns pay-load or INT_MIN if list is empty or searched pos is negativ*/
    
    int GetNode(Node *head, int positionFromTail)
    {
      int result = INT_MIN;
    
      ...
    
      while (head->next != NULL) {
        if(p == positionFromTail) {
          result = head->data;
          break;
        }
        else {
          p++;
          head = head->next;
        }
      } 
    
      return result;
    }